C # gridview binding list

I am trying to bind a list to gridview . The situation is this: I take the data from the .txt file, later I put it in the first List<Mycolumns> list. I have data in a list (with three separate columns) that I created. I am taking data from one of the columns called System_Description . Now I would like to show this data in a gridview , but only what I get is the length of each row. How to fix it? Here is my code.

 private void button7_Click(object sender, EventArgs e) { List<MyColumns> list = new List<MyColumns>(); OpenFileDialog openFile1 = new OpenFileDialog(); openFile1.Multiselect = true; if (openFile1.ShowDialog() != DialogResult.Cancel) { foreach (string filename in openFile1.FileNames) { using (StreamReader sr = new StreamReader(filename)) { string line; while ((line = sr.ReadLine()) != null) { string[] _columns = line.Split(",".ToCharArray()); MyColumns mc = new MyColumns(); mc.Time = _columns[0]; mc.System_Description = _columns[1]; mc.User_Description = _columns[2]; list.Add(mc); } } } DataTable ListAsDataTable = BuildDataTable<MyColumns>(list); DataView ListAsDataView = ListAsDataTable.DefaultView; this.dataGridView1.DataSource = view = ListAsDataView; this.dataGridView1.AllowUserToAddRows = false; dataGridView1.ClearSelection(); } List<string> description = list.Select(x => x.System_Description).ToList<string>(); this.dataGridView2.DataSource = description; } class MyColumns { public string Time { get; set; } public string System_Description { get; set; } public string User_Description { get; set; } } 

EDIT:

I read that DataBind() works for a web form, my application is a desktop application. What should I do now?

+4
source share
4 answers

I managed to solve this problem. I did it like this, maybe it will help someone. You can use DataTable and then bind DT to gridview.

 DataTable dt = new DataTable(); dt.Columns.Add("values"); foreach(string items in description) { DataRow row = dt.NewRow(); dt.Rows.Add(items); } this.dataGridView2.DataSource = dt; 
+1
source

this.dataGridView1.DataSource = new BindingSource(list);

+1
source

You select only the System_Description field using the following statement:

 List<string> description = list.Select(x => x.System_Description).ToList<string>(); 

Then you bind this list to gridview:

 this.dataGridView2.DataSource = description; 

If you want to bind all the data to a gridview ; just bind the list as a data source.

 this.dataGridView2.DataSource = list; this.dataGridView2.DataBind(); 
0
source

Use this

  this.dataGridView1.DataSource = description; 

and add the Bound field to gridview on aspx.

 <asp:BoundField DataField="System_Description" HeaderText="System_Description"></asp:BoundField> 
-one
source

Source: https://habr.com/ru/post/1492679/


All Articles