Reputation: 419
i have a function called ViewComments() which retrieve contents from database using SQL commands
private void ViewComments()
{
hookUp = new SqlConnection("Server=XXXX\\SQLEXPRESS;Database=WebExcerciseDB;" + "Integrated Security=True");
SqlCmd = new SqlCommand("SELECT PersonName,PersonMail,Comment FROM CommentsTable", hookUp);
try
{
hookUp.Open();
reader = SqlCmd.ExecuteReader();
while (reader.Read())
{
SQL_Result.Text += reader["PersonName"] + " " + reader["PersonMail"] + " " + reader["Comment"] + Convert.ToString(reader["PostDate"]) + "<br/>";
}
}
catch (Exception)
{
MessageBox.Show("Error in database code\n");
}
finally
{
reader.Close();
hookUp.Close();
}
}
i want to store the contents in IList<>
control, how to do that?
thanks any way..
Upvotes: 0
Views: 116
Reputation: 1613
Create a class that has properties for the values you want:
public class Comment
{
public string PersonName {get;set;}
public string PersonMail {get;set;}
public string Comment {get;set;}
public string PostDate {get;set;}
}
and then Create a List and fill it up with the values:
List<Comment> comments = new List<Comment>();
...
while (reader.Read())
{
comments.Add(new Comment()
{
PersonName = reader["PersonName"],
PersonMail = reader["PersonMail"],
Comment = reader["Comment"],
PostDate = Convert.ToString(reader["PostDate"])
});
}
Upvotes: 3
Reputation: 4537
You could also use LINQ to SQL to create the classes for you. You do this by:
Then, to query your database within code, you would do somthing such as:
private void QueryMyData()
{
MyDbmlFileNameDataContext context = new MyDbmlFileNameDataContext("Server=XXXX\\SQLEXPRESS;Database=WebExcerciseDB;" + "Integrated Security=True");
var query = from c in context.CommentsTable
where c.PersonName == "John Doe" // This is optional if you want to sub-select.
select c;
foreach (var comment in query)
{
Console.WriteLine(comment.PersonName + " " + comment.PersonMail + " " comment.Comment);
}
}
You can see more examples here or here.
WARNING: From my own personal experience, LINQ does not seem to be very efficient with extremely large data sets.
Upvotes: 1