C# Winform 将datatable作为数据源绑定到DataGridview后显示为空!
毕业设计
1
public DataTable dvtodt(DataGridView dv)
{
DataTable dt = new DataTable();
DataColumn dc;
for (int i = 0; i < dv.Columns.Count; i++)
{
dc = new DataColumn();
dc.ColumnName = dv.Columns[i].Name.ToString();
dt.Columns.Add(dc);
}
for (int j = 0; j < dv.Rows.Count; j++)
{
DataRow dr = dt.NewRow();
for (int x = 0; x < dv.Columns.Count; x++)
{
dr[x] = dv.Rows[j].Cells[x].Value;
}
dt.Rows.Add(dr);
}
return dt;
}
//将DataTable 作为数据源绑定dataGridView1,点击事件后dataGridView1 竟然显示为空!!!
private void btn1_Click(object sender, DataGridViewCellMouseEventArgs e)
{
DataTable d = new DataTable();
d = eo.dvtodt(dataGridView1);
BindingSource source = new BindingSource();
source.DataSource = d;
dataGridView_dpmt.DataSource = source;
}
//giegie们是哪里出问题了,整不明白了!
PS:我的DataGridView 用VS设置绑定了某个数据库的表作为数据源,会是这个原因吗?
-
测试了下在属性窗口中绑定过数据源重新设置DataSource无法覆盖原数据,但是可以新建一个datagridview,设置这个新datagridview的Location,Height,Width和原来的一样,删除dataGridView_dpmt,然后这个新建的datagridview进入form中,设置数据源可以自动绑定。
private void btn1_Click(object sender, EventArgs e) { DataTable d = new DataTable(); d = dvtodt(dataGridView1); BindingSource source = new BindingSource(); source.DataSource = d; var dg = new DataGridView(); dg.Location = new Point(dataGridView2.Location.X, dataGridView2.Location.Y); dg.Width = dataGridView2.Width; dg.Height = dataGridView2.Height; //如果放到其他容器中下面这2句的this要改为容器对象的Name this.Controls.Remove(dataGridView2); this.Controls.Add(dg); dg.DataSource = d; }
-
望采纳,谢谢,绑定数据的方法试一试
// DataSet 、DataTable // 方式1 DataSet ds=new DataSet (); this.dataGridView1.DataSource=ds.Table[0]; this.dataGridView1.DataSource = ds.Tables["表名"]; // 方式2 DataTable dt=new DataTable(); this.dataGridView1.DataSource=dt; // DataView DataView dv = new DataView(); this.dataGridView1.DataSource = dv; // 设置了DataMember DataSet ds=new DataSet (); this.dataGridView1.DataSource = ds; this.dataGridView1.DataMember = "表名"; // ArrayList ArrayList Al = new ArrayList(); this.dataGridView1.DataSource = Al; // dic Dictionary<string, string> dic = new Dictionary<string, string>(); this.dataGridView1.DataSource = dic; // List this.dataGridVi.DataSource = new BindingList(List);
发表回复