【问题标题】:Why the index of first row is picked when I click any row in gridview?为什么单击gridview中的任何行时会选择第一行的索引?
【发布时间】:2015-10-30 07:05:03
【问题描述】:

当我在任何行中单击 EDIT 时,为什么它会选择第一行的索引?

Gridiview 中的编辑按钮:

<asp:ButtonField CommandName="cmdEdit" HeaderText="Edit" ImageUrl="~/assets/global/images/shopping/edit.png" ButtonType="Image" ControlStyle-Width="25px" ControlStyle-Height="20px" />

编辑背后的代码:

protected void grdviewLandInfo_RowCommand(object sender, GridViewCommandEventArgs e)
{
    try
    {              
         int Index = Convert.ToInt32(e.CommandArgument);
         Int32 LandInfoID =  Convert.ToInt32(grdviewLandInfo.DataKeys[Index].Value);
         short UserID = Convert.ToInt16(Session["UserID"]);

         short LandTypeID = Convert.ToInt16(grdviewLandInfo.Rows[Index].Cells[6].Text);

【问题讨论】:

  • 这是因为你没有指定&lt;asp:ButtonField...的任何CommandArgument属性
  • 但在其他页面中我没有指定任何命令参数并且有效
  • 并且 CommantArgument 不是 buttonField 的属性
  • 那是因为CommandArgument 没有为按钮指定,所以e.CommandArgumentRowCommand 上为空,然后Convert.ToInt32 为空值返回 0,0 是您的第一行索引
  • 啊,现在有趣了,CommandArgument不是 ButtonField 的属性。从来没有使用过按钮域,我总是使用带有 CommandName 和 CommandArgument 的 LinkBut​​ton,所以研究一下。

标签: c# asp.net gridview webforms


【解决方案1】:

在 commandArgument 属性中添加按钮字段,如下所示。

<asp:ButtonField CommandName="cmdEdit" HeaderText="Edit" ImageUrl="~/assets/global/images/shopping/edit.png" CommandArgument='<%# ((GridViewRow) Container).RowIndex %>' ButtonType="Image" ControlStyle-Width="25px" ControlStyle-Height="20px" />

【讨论】:

  • 但在其他页面中我没有指定任何命令参数并且有效
【解决方案2】:

试试这个:

protected void grdviewLandInfo_RowCommand(object sender, GridViewCommandEventArgs e)
{
  if(e.CommandName == "cmdEdit")
   {
    try
    {  
       ...

【讨论】:

  • 不,问题出在 IF 语句之前,它没有选择正确的 INDEX
【解决方案3】:

试试这个...

if (e.CommandName.Equals("cmdEdit"))
{
        GridViewRow row = (GridViewRow)((Control)e.CommandSource).Parent.Parent;
    Int32 LandInfoID =  Convert.ToInt32(grdviewLandInfo.DataKeys[row.RowIndex].Value);
}

希望这会有所帮助...

【讨论】:

    猜你喜欢
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-07
    • 1970-01-01
    相关资源
    最近更新 更多