如何通过自动填充文本

时间:2016-10-12 16:12:22

标签: c# datagridview

我创建了一个应用程序,其中medicine_name是自动完成文本,基于该选择我想填充Expiry_Date但是每当我运行代码时它给出我索引超出了数组异常的范围,检索我写在dataGridView1_CellEndEdit事件上的代码我不知道我在哪里错了我粘贴我的代码和应用程​​序和表结构的屏幕截图

private void dataGridView1_CellEndEdit_1(object sender, DataGridViewCellEventArgs e)
        {

 string connectionString = null;
            connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
            con.ConnectionString = connectionString;


            string medicinename = Convert.ToString(dataGridView1.Rows[e.RowIndex].Cells["Medicine_name"].Value);
            DateTime Expiry_Date = Convert.ToDateTime (dataGridView1.Rows[e.RowIndex].Cells["Expiry_Date"].Value);

            con.Open();
            cmd = new OleDbCommand("select Expiry_Date from Medicine_Available_Detail where Medicine_Name='" + medicinename + "'", con);
            OleDbDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                Expiry_Date = Convert.ToDateTime (dr.GetValue(5));// exeception coming on this line
            }
            con.Close();


        }

enter image description here enter image description here

1 个答案:

答案 0 :(得分:0)

我得到了解决方案。

string connectionString = null;
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;


string medicinename = Convert.ToString(dataGridView1.Rows[e.RowIndex].Cells["Medicine_name"].Value);
DateTime Expiry_Date=new DateTime (); 

con.Open();
cmd = new OleDbCommand("select Expiry_Date as Expiry_Date from Medicine_Available_Detail where Medicine_Name=@Medicine_Name",con);
cmd.Parameters.AddWithValue("@Medicine_Name",medicinename);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
    Expiry_Date = Convert.ToDateTime(dr["Expiry_Date"]);

}
dataGridView1.Rows[e.RowIndex].Cells["Expiry_Date"].Value = Expiry_Date; 
con.Close();