简体   繁体   中英

Populate data manually on my dataGridView from sql table

I am a newbie on c#.I want to bind my sql columns to my dataGridView columns manually. I dont want to assign datatable as below.

SqlDataAdapter da = new SqlDataAdapter();
                        da.SelectCommand = cmd;
                    DataTable dt = new DataTable();
                    da.Fill(dt);

                    dgvAttendance.DataSource = dt;

All I want to bind sql column to datagridview column by calling their name. I want that because I need a dataGridViewCheckBoxColumn to be added on the left of my columns. but if I add that dataGridViewCheckBoxColumn column before assigning the data source, this column take place on 0 index. I need it to be on the right most column.

*I need both of the solution.

You can use SqlDatareader instead as follows (assuming you have 3 columns):

DataTable dt = new DataTable();
DataGridTableStyle tableStyle = new DataGridTableStyle();
dt.Columns.Add(new DataColumn("ColumnName1", typeof(string)));
dt.Columns.Add(new DataColumn("ColumnName2", typeof(string)));
dt.Columns.Add(new DataColumn("ColumnName3", typeof(string)));
columnStyle = new DataGridTextBoxColumn();
columnStyle.Width = 50;
columnStyle.MappingName = "ColumnName1";
columnStyle.HeaderText = "ColumnName1";
tableStyle.GridColumnStyles.Add(columnStyle);
DataGridTextBoxColumn cs;
cs = new DataGridTextBoxColumn();
cs.MappingName = "ColumnName2";
cs.Width = 160;
cs.HeaderText = "ColumnName2";
tableStyle.GridColumnStyles.Add(cs);
DataGridTextBoxColumn cs2;
cs2 = new DataGridTextBoxColumn();
cs2.MappingName = "ColumnName3";
cs2.Width = 100;
cs2.HeaderText = "ColumnName2";
tableStyle.GridColumnStyles.Add(cs2);
dataGrid1.TableStyles.Clear(); ///dataGrid1 is the name of your DataGridView
dataGrid1.TableStyles.Add(tableStyle);        
SqlDataReader reader = cmd.ExecuteReader();
DataRow dr;
while (reader.Read())
{
    dr = dt.NewRow();
    dr[0]=reader[0].ToString();
    dr[1]=reader[1].ToString();
    dr[2]=reader[2].ToString();
}
DataView dv = new DataView(dt);
dataGrid1.DataSource =dv;
reader.Close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM