1

I have a query that selects 3 columns from a SQL table, I need to export the resulting query into a listview. I don't need any help with the SQL setup, just how to format it into the listview. There is where I am stuck. Any help is appreciated. Thanks!

string sql = "select distinct pro,ds,date from dbo.Sge where date IN (select max(date) from dbo.Storage) order by project"; SqlConnection con = new SqlConnection("Data Source= ;Initial Catalog= ;Integrated Security= SSPI"); con.Open(); DataSet ds = new DataSet(); SqlDataAdapter adapter = new SqlDataAdapter(sql,con); adapter.Fill(ds); foreach (DataRow row in ds.Tables[0].Rows) { for(int i=0; i< ds.Tables[0].Columns.Count; i++)) } 

Edit: Sorry guys, i mentioned ListBox originally and i meant ListView. My ListView is detailed and had a column for each of my columns in my select, i just simply need the SQL export to go to the right column.

This is what I have come up with, but it doesn't add to each column, just to the first column

foreach (DataRow row in poplb6ds.Tables[0].Rows) { listView1.Items.Add(row["Pro"].ToString()); listView1.Items.Add(row["size"].ToString()); listView1.Items.Add(row["Date"].ToString()); } 
2
  • i understand i need Subitems, just not sure how to piece it together. Commented Nov 30, 2010 at 15:45
  • System.Windows.Forms.FormsListView or System.Web.UI.WebControls.ListView? WinForms or ASP.NET? Commented Nov 30, 2010 at 16:12

4 Answers 4

3

The following assumes that your ListView has columns in the order |Pro|Size|Date|

foreach (DataRow row in poplb6ds.Tables[0].Rows) { ListViewItem item = new ListViewItem(row["Pro"].ToString()); item.SubItems.Add(row["size"].ToString()); item.SubItems.Add(row["Date"].ToString()); listView1.Items.Add(item); } 
Sign up to request clarification or add additional context in comments.

Comments

0

The standaard solution would be: listbox1.DataSource = poplb6ds; If you need any specific formatting, please elaborate on that.

1 Comment

I have a detailed view in which each need to go into the appropriate list for my listview, and i do apologize, i am using listview
0

Check this out:

C# listView, how do I add items to columns 2, 3 and 4 etc?

Comments

0
  1. Use using blocks:

    using (SqlConnection con = new SqlConnection("Data Source=;Initial Catalog= ;Integrated Security= SSPI")) { con.Open(); using (DataSet ds = new DataSet()) { using (SqlDataAdapter adapter = new SqlDataAdapter(sql, con)) { adapter.Fill(ds); } } } 
  2. Fill single table:

    DataTable dt = new DataTable(); // new DataTable("Sge"); name it if will be required adapter.Fill(dt); 
  3. Your loop has makes no sense because columns are the same for each row in the table:

    foreach (DataColumn column in dt.Columns) { } 
  4. Or you want to iterate thru each row and each column?

    foreach (DataColumn column in dt.Columns) { foreach (DataRow row in dt) { object value = row[column]; } } 

Comments