Click here to Skip to main content
15,909,091 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all ,

I have one datagridview which is not connect to to the database only one column is which is select from table and after confirming it backend it update -1 , means Medicine name is XYZ after selecting and confirming it should be 22-1 is 21 i have done coding for that but its showing me Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index exception on string medicinename = dataGridView1.SelectedRows[0].Cells["Medicine_Name"].Value.ToString();

in datagridview im not showing total_available column its should be update when user selected particular medicine

What I have tried:

C#
string connectionString = null;
            connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
            con.ConnectionString = connectionString; 
            string medicinename = dataGridView1.SelectedRows[0].Cells["Medicine_Name"].Value.ToString();
            
            DialogResult dialogResult = MessageBox.Show("Are you sure you want to insert data", "Data insert Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
            if (dialogResult == DialogResult.Yes)
            {
                cmd = new OleDbCommand("update Medicine_Available_Detail set [total_available]=total_available-1 where [Medicine_Name]=@Medicine_Name", con);
                //cmd.Parameters.AddWithValue("@total_available", medicineavailable);
                cmd.Parameters.AddWithValue("@Medicine_Name", medicinename);
                con.Open();
                int n = cmd.ExecuteNonQuery();
                con.Close();
                MessageBox.Show("Record Updated Successfully");
                showdata();
                dataGridView1.Refresh();



            }
Posted
Updated 25-Jun-16 4:44am
v2

1 solution

You need to start with the debugger and see exactly what you are dealing with - the chances are that the SelectedRows property is returning an empty list and thus doesn't have an element at row zero so you get a bad index exception.
But we can't test it: we don't have access to your PC or your data.
So put a breakpoint on the line, and look at exactly what you have when it executes.
It's very likely that the error itself isn't in that code, but in whatever is supposed to be filling the DataGridView or selecting one or more rows. We can't tell, and we don't have the code.
So use the tools you have to look at exactly what is going on while the code is running and you should be able to work it out.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900