How to Bind specific Columns of a datatable to a DataGridView?

为君一笑 提交于 2019-12-28 13:36:31

问题


My DataTable has three columns fetched from a database, while I need to bind only two columns of it to a DataGridView. Can you please help me with it?


回答1:


Create the columns for the DataGridView yourself. Try something like this.

DataGridView dataGridView1 = new DataGridView();
BindingSource bindingSource1 = new BindingSource();

dataGridView1.ColumnCount = 2;

dataGridView1.Columns[0].Name = "Field1";
dataGridView1.Columns[0].DataPropertyName = "Field1";
dataGridView1.Columns[1].Name = "Field2";
dataGridView1.Columns[1].DataPropertyName = "Field2";

bindingSource1.DataSource = GetDataTable();
dataGridView1.DataSource = bindingSource1;



回答2:


Add the column as answered above, and do not forget to set:

dataGridView1.AutoGenerateColumns = false;



回答3:


private void Form1_Load(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("connection string");
        SqlDataAdapter adp = new SqlDataAdapter("select  Fieldname1,fieldname2 from Table Name", con);
        DataSet ds = new DataSet();
        ds.Clear();
        adp.Fill(ds);
        if (ds.Tables[0].Rows.Count > 0)
        {
            dataGridView1.DataSource = ds.Tables[0];
  }

Definitely it will work.




回答4:


This was asked a while ago, so you probably won't need this answer... Hopefully others will find it useful.

I had to do something similar, and I found that the simplest solution was to create a temporary copy of the table (in which your data is stored) and then to simply remove the column in question. For example:

DataTable temp = YourDataTable;
temp.Columns.Remove(temp.Columns[2]) // Will remove the third column for example
YourDataTable.DataSource = temp;
YourDataTable.DataBind();

I think this should do the trick!

Cheers!




回答5:


We can create a new DataTable with the required Columns and add rows to it from the Dataset. Then we can initialize the DataGrid with the Newly Created DataTable.

dt = new DataTable();          
dt_Property.Columns.Add("Field1");
dt_Property.Columns.Add("Field2");
int i = 0;
DataRow row = null;
foreach (DataRow r in ds.Tables[0].Rows)
{               
    row = dt.NewRow();                    
    row["Field1"] = ds.Tables[0].Rows[i][1];
    row["Field2"] = ds.Tables[0].Rows[i][2];
    dt_Property.Rows.Add(row);   
    i = i + 1;
}

dataGridView1.DataSource = dt;



回答6:


Bind DataTable to DataGridView after that hide the column you don't want.

dataGridView1.DataSource = datatable;
dataGridView1.Columns["ColumnName"].Visible = false;


来源:https://stackoverflow.com/questions/4907429/how-to-bind-specific-columns-of-a-datatable-to-a-datagridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!