I am retrieving 4 Fields from my database table. Now i want to add them to a dynamic list <>. How to add those into the list.
I tried this :
public class myclass
{
public string StdDetails, StdAdderID;
public DateTime StdAddedDate, StdAddedTime;
}
public void buttonClick()
{
List<myclass> StdList = new List<myclass>();
myclass mc = new myclass();
OdbcCommand readStd =
new OdbcCommand("SELECT StdDetails, StdAddedDate," +
"StdAddedTime, StdAdderID" +
"FROM Students", Conn);
OdbcDataReader readStdreader =
readStd.ExecuteReader(CommandBehavior.SingleRow);
while (readStdreader .Read())
{
mc.StdDetails = readStdreader.GetString(0);
mc.StdDetails = readStdreader.GetString(3);
mc.StdDetails = readStdreader.GetDate(1);
mc.StdDetails = readStdreader.GetDateTime(2);
StdList.Add(mc);
}
MessageBox.Show(StdList[0].ToString());
}
In the message box the value isn’t displayed? what to do.please help
//SORRY FOR THE TYPOS :
replace these 3 lines :
mc.StdDetails = readStdreader.GetString(3);
mc.StdDetails = readStdreader.GetDate(1);
mc.StdDetails = readStdreader.GetDateTime(2);
with :
mc.StdAddedDate= readStdreader.GetString(3);
mc.StdAdderID= readStdreader.GetDate(1);
mc.StdAddedTime= readStdreader.GetDateTime(2);
You’re only creating a single instance of
myclass, so your list will be full of references to the same object. You want this instead:Note how I’ve changed the properties that are assigned, too – the code you posted attempts to assign to
StdDetailsrepeatedly.You also haven’t overridden
ToStringinmyclass, so callingToString()isn’t going to give you anything particularly useful.Additionally:
stdmean here? You’ve used it for almost everything…)usingstatements to close readers, commands, connections etc in a reliable way.