user1947927
user1947927

Reputation: 190

Getting value of a column of gridview

I want to take a control as column in the TemplateFeilds of Gridview and it should not be hidden. There is a Button in the end of every column. My question is that what control i should use and how to get the value of specific row of that column where a Button is clicked in the Gridview.

Upvotes: 3

Views: 792

Answers (4)

Suraj
Suraj

Reputation: 85

Use hidden field in your template.

Upvotes: 2

Himanshu
Himanshu

Reputation: 716

You should use HiddenField as column in the GridView because the control wont be visible and thus fulfil your requirement. The code behind will be inside the row command of gridview

   public  void gdView_RowCommand(object sender, GridViewCommandEventArgs e)
        {

            if (e.CommandName == "sendvalue")
            {

                for (int i = 0; i < gdView.Rows.Count; i++)
                {
                    int getrow = Convert.ToInt32(e.CommandArgument);

                    HiddenField HiddenField1 = (HiddenField)gdView.Rows[getrow].FindControl("HiddenField1");
}
}

where e.CommandName == "sendvalue" is because the atrribute command name of Button is set to be "sendvalue"

HiddenField in design will be as

  <asp:HiddenField ID="HiddenField1" runat="server"/>

Upvotes: 3

Tim Schmelter
Tim Schmelter

Reputation: 460288

What value do you want to get?

You can handle the button's click event and cast the sender to Button and it's NamingContainer to GridViewRow. Then you have all you need to find all the other controls in that row.

protected void Button1_Clicked(Object sender, EventArgs e)
{
    // get the button reference
    Button btn = (Button) sender;
    GridViewRow row = (GridViewRow) btn.NamingContainer;
    // assuming the primary key value is stored in a hiddenfield with ID="HiddenID"
    HiddenField hiddenID = (HiddenField) row.FindControl("HiddenID");
    int id = int.Parse(hiddenID.Value);
}

aspx (GridView's TemplateField)

<asp:Button ID="Button1" runat="server" Text="Click Me" OnClick="Button1_Clicked"/>
<asp:HiddenField ID="HiddenID" runat="server" Value='<%# Eval("PrimaryKeyField") %>'/>

Upvotes: 3

Roland Mai
Roland Mai

Reputation: 31097

You can change your approach by setting the CommandArgument property, of the button that will be clicked, to the value you want during row data binding.

Upvotes: 2

Related Questions