I am making a web site in visual studio 2012, using asp.net, c#. I created a grid view, which is taking data from my sql server, and created a button field which is bound to id_p, which is one of the collumns taken from a database. I am trying to get the data of the id_p for the row in which the button was clicked.

<asp:ButtonField ButtonType="Button" DataTextField="id_p" 
DataTextFormatString="Stavi u košaricu" Text="Button1" />

What I need is not the selected row, only the id_p value, so how could I do that, please?

有帮助吗?

解决方案

You need to handle the OnRowCommand Event on the gridview as so:

<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView_RowCommand" 

And create a ItemTemplateField to display a regular <asp:button> instead of using the ButtonField column:

<asp:TemplateField>
     <ItemTemplate>
         <asp:Button ID="btn" runat="server" 
          CommandName="Something" CommandArgument='<%#Eval("id_p") %>'
          Text="Stavi u košaricu" />
     </ItemTemplate>
 </asp:TemplateField>

Now you handle the RowCommand Event:

protected void GridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
    string m_id = e.CommandArgument.ToString();
    if (e.CommandName == "Something")
    {
       //do something with m_id
    }
}    
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top