Click here to Skip to main content
16,005,339 members
Please Sign up or sign in to vote.
1.50/5 (2 votes)
See more:
I try to get the id value from selected row and when i run the code i get the value or id is null. Here is my code, please help me.

C#
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "Select")
                {
                    MultiView1.ActiveViewIndex = 1;
                    GridView1.Visible = true;

                    int index = Convert.ToInt32(e.CommandArgument.ToString());

                    string id = GridView2.DataKeys[index].Value.ToString();
                    var emp = db.tb_Employees.Where(x => x.Employee_id == id).FirstOrDefault();

                    if (emp != null)
                    {
                        text_editname.Text = emp.Name;
                        text_editaddress.Text = emp.Address;
                        text_editemail.Text = emp.Email;
                        text_editphone.Text = emp.Phone;
                        DropDownList2.SelectedValue = emp.Division_id;
                    }
                }
            }
            catch (Exception)
            { }


        }


I get :
Exception : "Index was out of range. Must be non-negative and less than the size of the collection."(System.ArgumentOutOfRangeException)
Posted
Comments
[no name] 15-Sep-13 11:21am    
It simply means that you are trying to access an element of an array or collection that does not exist. Probably in GridView2.DataKeys[index].Value.ToString();
PIEBALDconsult 15-Sep-13 12:03pm    
Also check the value of e.CommandArgument
Sergey Alexandrovich Kryukov 15-Sep-13 12:15pm    
Use the debugger. Your problem is way too simple.
When asking a question with exception, please always comment the line where the exception is thrown and provide comprehensive exception information. Your case is simple: you show only one place with indexing "[index]".
—SA

1 solution

Hello

The cause of this error is that the event handler is of "GridView1" whereas the datakey retrieval is of "GridView2"

Obviously the result won't match :)
 
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