日期:2014-05-20  浏览次数:20912 次

winform dataGridView动态添加DataGridViewTextBoxColumn 录入数据获取值
C# code

for (int i = 0; i < 5; i++)
{
   DataGridViewTextBoxColumn text = new DataGridViewTextBoxColumn();
   text.Name = ds1.Tables[0].Columns[i].ColumnName;
   text.DataPropertyName = ds1.Tables[0].Columns[i].ColumnName;
   dataGridView1.Columns.Add(text);
}   DataGridViewTextBoxColumn text1 = new DataGridViewTextBoxColumn();
   text1.HeaderText = "药品数量";
   text1.Name = "MedicineNum";
   text1.DataPropertyName = "MedicineNum";
   dataGridView1.Columns.Add(text1);
   dataGridView1.DataSource = ds1.Tables[0];
   ds1.Tables[0].Columns.Add(new DataColumn("MedicineNum", typeof(int)));
   dataGridView1.Columns["MedicineCode"].HeaderText = "药品编号";
   dataGridView1.Columns["MedicineName"].HeaderText = "药品名称";
   dataGridView1.Columns["MedicineSpec"].HeaderText = "规格";
   dataGridView1.Columns["MedicineInfo"].HeaderText = "使用病症";
   dataGridView1.Columns["Remark"].HeaderText = "备注信息";


先根据datasouce创建5列,然后额外增加一列,这里录入数据并获取录入的值,总是报未将对象引用设置到对象的实例,请问如何正确的实现该功能,谢谢
C# code

for (int j = 1; j <= dataGridView1.Rows[i].Cells.Count; j++)
{
    if (this.dataGridView1.Columns[j].HeaderText.ToString() == "药品数量")
    {
       string StrNum = dataGridView1.Rows[1].Cells["MedicineNum"].Value.ToString();
//在上一行报错
      if (StrNum != "" && StrNum != "0")
     {
        string SqlStr = "insert into [*] (###) values ('" + #+ "','" + #+ "','" + #+ "')";
        sqlconn.ExecuteNoQuery(SqlStr);
        MessageBox.Show("信息添加成功", "系统提示");
      }
      else
      {
         MessageBox.Show("请输入药品数量", "系统提示");
      }
    }
}



------解决方案--------------------
一次检查
dataGridView1.Rows[1]
dataGridView1.Rows[1].Cells["MedicineNum"]
dataGridView1.Rows[1].Cells["MedicineNum"].Value
是否为空