无法在桌面应用程序背后的代码中绑定网格视图

2024-02-28

我有一个列出所有客户的网格视图。

我将它绑定在放置在 MDI 子项中的 Form 的加载时间中。

网格视图中的列是在设计时预定义的。

我的代码Form_Load()事件是:

try
{
       cn = db.createConnection();
       if (cn.State == System.Data.ConnectionState.Open)
       {
           cn.Close();
       }
       cn.Open();
       cmd = new OleDbCommand("Select BillNo,PartyName,City,State,FORMAT(BillDt,'dd-mm-yyyy') as BillDt from BillMaster", cn);
       da = new OleDbDataAdapter(cmd);
       ds = new DataSet();
       da.Fill(ds);
       cn.Close();

       dataGridView1.AutoGenerateColumns = false;
       dataGridView1.DataSource = ds.Tables[0];
       for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
       {
            dataGridView1.Rows[i].Cells[0].Value = ds.Tables[0].Rows[i]["BillNo"].ToString();
            dataGridView1.Rows[i].Cells[1].Value = ds.Tables[0].Rows[i]["PartyName"].ToString();
            dataGridView1.Rows[i].Cells[2].Value = ds.Tables[0].Rows[i]["City"].ToString();
            dataGridView1.Rows[i].Cells[3].Value = ds.Tables[0].Rows[i]["State"].ToString();
            dataGridView1.Rows[i].Cells[4].Value = ds.Tables[0].Rows[i]["BillDt"].ToString();
        }

   }
   catch (Exception ex)
   {
        MessageBox.Show(ex.Message.ToString());
   }
   finally
   {
       cn.Close();
       da.Dispose();
       ds.Dispose();
       cmd.Dispose();
   }

}

我通过设置断点来检查程序的执行情况。数据的获取与数据集中的数据库完全相同,网格的特定单元格的值显示精确的值,但问题是加载表单时网格仍为空。并创建与从数据库中获取的行数相同的空白行数。

我应该做什么来解决这个错误。

请帮忙。


Change

dataGridView1.AutoGenerateColumns = false;

to true. Remove

for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
   {
        dataGridView1.Rows[i].Cells[0].Value = ds.Tables[0].Rows[i]["BillNo"].ToString();
        dataGridView1.Rows[i].Cells[1].Value = ds.Tables[0].Rows[i]["PartyName"].ToString();
        dataGridView1.Rows[i].Cells[2].Value = ds.Tables[0].Rows[i]["City"].ToString();
        dataGridView1.Rows[i].Cells[3].Value = ds.Tables[0].Rows[i]["State"].ToString();
        dataGridView1.Rows[i].Cells[4].Value = ds.Tables[0].Rows[i]["BillDt"].ToString();
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法在桌面应用程序背后的代码中绑定网格视图 的相关文章

随机推荐