使用相同命令的两个asp:Command列的GridView控件

时间:2009-06-03 17:36:47

标签: c# asp.net gridview

我有一个带有两个GridView列的ASP.NET asp:CommandField控件,它们都使用Select命令执行不同的任务。当我检查OnRowCommand对象的CommandName属性时返回“选择”时,如何区分GridViewCommandEventArgs事件中选择的列?

这是我的源代码:

ASPX页面:

<asp:GridView ID="MyGridView" runat="server" AutoGenerateColumns="false" OnRowCommand="MyGridView_OnRowCommand">
    <Columns>
        <asp:CommandField ButtonType="Link" ShowSelectButton="true" SelectText="Click Me!" />
        <asp:CommandField ButtonType="Link" ShowSelectButton="true" SelectText="No Click Me!" />
    </Columns>
</asp:GridView>

代码背后:

protected void MyGridView_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
    string x = e.CommandName //returns "Select" for both asp:CommandField columns
}   

5 个答案:

答案 0 :(得分:4)

使用按钮列,这样您可以指定特定的命令名称并从那里使用

<asp:ButtonField ButtonType="Link" Text="Click Me" CommandName="MyCommand1" />
<asp:ButtonField ButtonType="Link" Text="No Click Me" CommandName="MyCommand2" />

然后您可以根据e.CommandName

采取行动

答案 1 :(得分:0)

使用GridViewCommandEventArgs。CommandArgument属性!

答案 2 :(得分:0)

那么,首先你必须使用SELECt作为命令吗?您可以将其设置为更有意义的其他内容。

其次,您可以将CommandArgument属性设置为不同的值,以便您知道正在单击哪一个。

答案 3 :(得分:0)

使用命令参数属性。

e.commandargument

或者您可以在命令字段中动态创建按钮,并将commandName设置为您想要的任何内容。

gridview_Load中的

for (int i = 0; i <= GridView1.Rows.Count - 1; i++) {

    linkbutton btnedit = new linkbutton();


    GridView1.Rows(i).Cells(3).Controls.Add(btnedit);
   //the above is where you want the button to be on the grid
    btndel.CommandName = "Select2";
    btndel.CommandArgument = "whatever you want";
}

Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
    If e.CommandName = "Select1" Then 

       //do stuff
End Sub

答案 4 :(得分:0)

您寻求的答案简单而棘手。我的网站项目也遇到了这个问题,所以我在互联网上浏览了几天而没有找到我和你需要的东西。

有一天,我只是单独考虑了问题并进行了几个小时的实验,最后意识到了解按钮被点击的列的唯一简单方法是在RowCommand event的{​​{1}}中GridView的{​​{1}}。更准确地说,可能更舒适的是通过设计模式编辑CommandName property的列,并将命令字段替换为按钮字段。

您可以在GridViewCommandEventArgs中为每个按钮字段提供任何GridView,因此在string/text事件中您可以知道点击了哪个。 CommandNameRowCommand,但您不想提供这些字符串,因为您请求按钮应该选择并提供给您的内容,因此Button1应该是选择,但也可以选择选择选择等等。

可以在Button2中以多种形式提及select命令,系统仍会识别它。例如,如果CommandName中有两个按钮字段,其第一个CommandName只是选择,另一个是 SELECT < / strong>,然后点击其中任何一个时GridView事件加注并

CommandName

RowCommand的{​​{1}}将包含您请求的数据。通过将按钮1​​设置为if (e.CommandName == "select") { Label1.Text = "You clicked first button"; } else { Label1.Text = "You clicked second button"; } 并将按钮2设置为SelectedDataKey,其他人在回答中提供的内容与GridView不同,将有助于您了解是否点击了CommandName或另外,select_one的{​​{1}}将保留select_twoselect_one不包含您所需信息的实例。

换句话说,按钮不会选择任何必要的信息,因此按照我的回答非常重要。它是解决您问题的完美,完美和出色的解决方案!