Tuesday, March 10, 2009

Retrieve gridview values using via "NamingContainer"

Retrieve gridview values using via "NamingContainer

Simple tutorial on asp.net using c#

This tutorial tackles on retrieving row values using "NamingContainer".
 
Scenario: You have a gridview with a bunch of data from the DB. In your gridview you have a LinkButton named "Edit".
When you click on the "Edit" button, values from the selected row will be shown in a Textbox.

Their are a lot of approach to this kind of problem. One of which is assigning and ID to the commandArgument
of your LinkButton during Binding. You can also have the selected index.

This code will illustrate how to achieve same result by using the "NamingContainer".

    protected void btnEdit_Click(object sender, EventArgs e)
    {
        string fname, lname, addr, phone;//Some variable declarion

        LinkButton edit = ((LinkButton)sender);//Cast your sender to LinkButton to get the source of the event.

        GridViewRow gr = (GridViewRow)edit.NamingContainer;//Get the container of the Link Button and Cast it to GridviewRow.

   //Get cell value from the GridviewRow
        fname = gr.Cells[0].Text;
        lname = gr.Cells[1].Text;
        addr = gr.Cells[2].Text;
        phone = gr.Cells[3].Text;
   //Assign it to your textboxes
        this.txtFname.Text = fname;
        this.txtLname.Text = lname;
        this.txtAddress.Text = addr;
        this.txtPhone.Text = phone;
    }

No comments: