简体   繁体   English

DataGridView数据绑定和手动列

[英]DataGridView databound and manual column

I have a DataGridView on a form in c#, of the 7 columns i need on this DGV 6 of them will be pulled from an SQL DB and 1 of them i need to manually enter and its a link column . 我在c#的窗体上有一个DataGridView ,在此DGV上我需要的7列中有6列将从SQL DB中拉出,其中1列我需要手动输入,其链接列。 One thing i have going for me (i think) is that the manual column have the same data in every row. 我想为我做的一件事是,手动列的每一行都有相同的数据。

I have been filling this DGV using a datatable, but i am not figuring out how to add manual columns and data bound ones in the same DGV. 我一直在使用数据表填充此DGV,但我没有弄清楚如何在同一DGV中添加手动列和数据绑定的列。 My column layout would look like this: 我的列布局如下所示:

Column1 - DB Populated 列1-填充的数据库

Column2 - DB Populated 列2-填充的数据库

Column3 - DB Populated 列3-填充的数据库

Column4 - DB Populated 列4-填充的数据库

Column5 - DB Populated 列5-填充的数据库

Column6 - DB Populated 列6-填充的数据库

Column7 - Manually Populated 列7-手动填充

Can someone please explain to me how i would do something like this. 有人可以向我解释我将如何做这样的事情。 if you can include the datatable definitions also it would be a big help, in order for me to verify that i am at least doing that the right way. 如果您可以包括数据表定义,那也将是一个很大的帮助,以便让我验证我至少在以正确的方式进行操作。

Do not know why this should be so difficult - do not keep any columns initially in the Datagrid. 不知道为什么这应该如此困难-最初不要在Datagrid中保留任何列。 Bind it to a datasource and then add your columns manually 将其绑定到数据源,然后手动添加列

private void button1_Click(object sender, EventArgs e)
{
    con.Open();
    SqlCommand com = new SqlCommand("select * from yourtable", con);
    SqlDataAdapter adp = new SqlDataAdapter(com);
    DataSet ds = new DataSet();
    adp.Fill(ds);
    dataGridView1.DataSource = ds.Tables[0];
    dataGridView1.Columns.Add("manualcolumn", "manualcolumn");
}

Alternatively: 或者:

private void button1_Click(object sender, EventArgs e)
{
    con.Open();
    SqlCommand com = new SqlCommand("select * from yourtable", con);
    SqlDataAdapter adp = new SqlDataAdapter(com);
    DataTable dt = new DataTable();
    adp.Fill(dt);
    dataGridView1.DataSource = dt;
    dataGridView1.Columns.Add("manualcolumn", "manualcolumn");
}

con is SqlConnection conSqlConnection

Please refer This Link 请参考此链接

I hope this will give you a hint on adding dynamic columns to Grid-view. 我希望这会给您一个向Grid-view添加动态列的提示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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