views:

88

answers:

1

How do I pass a GridView column value to the code behind with out making it visible? In the following code, I would like to capture the ContactID with out making it visible in the GridView.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
    DataSourceID="SqlDataSource1" 
    OnRowCommand="_OnRowCommand"

    >
    <Columns>
        <asp:BoundField DataField="ContactID" HeaderText="ContactID" 
            SortExpression="ContactID" InsertVisible="False" ReadOnly="True" />


.....other columns in the grid....

        <asp:ButtonField ButtonType=Button CommandName="Remove" Text="Remove" />
    </Columns>
</asp:GridView>

I would like to capture ContactID as follows. I can not do so with out making it visible = true in the GridView.

if (e.CommandName.Equals("Remove"))
{
    int index = Convert.ToInt32(e.CommandArgument);
    int ContactID = Convert.ToInt32(GridView1.Rows[index].Cells[0].Text.Trim());
}

Please help.

Thanks..

+1  A: 

What you want and what your code is doing are two different things.

I think what you are looking for is this:

String ContactID = e.Row.Cells(0).Text;

However, I propose a different way:

You can use a CommandArgument on your Button. That means that you are passing the argument through the Button itself. You won't need to get the argument from any other control. To do that, you would do this :

    <asp:ButtonField ButtonType=Button CommandName="Remove" Text="Remove" CommandArgument='<%# Eval("ContactID") %>' />

And then your code looks like this:

 if (e.CommandName.Equals("Remove"))
 {
     int ContactID = Convert.ToInt32(e.CommandArgument);
 }

Here's a good example of GridView with CommandArguments.

rlb.usa
I tried the above code and it did not work for me. I get the following error:Databinding expressions are only supported on objects that have a DataBinding event. System.Web.UI.WebControls.ButtonField does not have a DataBinding event.
dotnet-practitioner
Why are you using a ButtonField. Try `<asp:Button` instead of `<asp:ButtonField`
rlb.usa
The above code worked after I turned button field into template field.. <asp:TemplateField HeaderText="Hide Message"> <ItemTemplate> <asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="Select" Text="Hide" CommandArgument='<%# Eval("ContactID") %>' /> </ItemTemplate> </asp:TemplateField>
dotnet-practitioner