Atul Atul - 1 month ago 11
C# Question

how to retrieve value in datagridview by autocomplete text

Iam creating one application where medicine_name is autocomplete text, base on that selection i want to populate Expiry_Date but whenever i run the code its given me Index was outside the bounds of the array exception, retrieve code i written on dataGridView1_CellEndEdit event i dont know where is im wrong here im pasting my code and screen shots of application and table structure

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

Answer

here is i got solution i think no one help me here but this could be help others

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();