【问题标题】:Access gridview cells访问 gridview 单元格
【发布时间】:2014-01-28 06:15:27
【问题描述】:

如何访问特定选定和选中行的 gridview 单元格。下面是代码

<asp:GridView ID="GridView1" runat="server" AutoGenerateSelectButton="True">
 <Columns>
     <asp:TemplateField HeaderText="IsApproved">
         <ItemTemplate>
           <asp:CheckBox ID="chkApproved" runat="server" CommandName="Approve" />
         </ItemTemplate></asp:TemplateField></Columns></asp:GridView>
 <asp:RadioButtonList ID="RadioButtonList1" runat="server"  RepeatDirection="Horizontal">
    <asp:ListItem Text="Approve" Value="1"></asp:ListItem>
    <asp:ListItem Text="Reject" Value="2"></asp:ListItem>
</asp:RadioButtonList>

gridview 的数据源由Page_Load 上的强类型数据集设置。现在在 btnSubmit 上,如果选中,我想将所选行插入到我的数据库表中

protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (RadioButtonList1.SelectedValue == "1")
        {
            foreach (GridViewRow row in GridView1.Rows)
            {
                var chk = row.FindControl("chkApproved") as CheckBox;
                   if (chk.Checked)
                    {
                      DataSet1TableAdapters.tbl_ApproveTableAdapter ta = new DataSet1TableAdapters.tbl_ApproveTableAdapter();
                      DataSet1.tbl_ApproveDataTable dt = new DataSet1.tbl_ApproveDataTable();
                      ta.Insert()// here I've to specify the cells of GV
                    }
            }
        }
    }
<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" />

这里有两个问题

i) 如果在复选框中选中该行,则访问 gridview 单元格

ii) 在我的 GV 选择中,它自动设置为 AutoPostback,我想禁用它,因为它正在清除选定的复选框。 .

【问题讨论】:

  • 您获取选中复选框的代码运行良好。您能告诉我们您在 GridView 中绑定了哪些事件吗?我认为 ItemCommand 会被绑定?

标签: c# asp.net .net gridview


【解决方案1】:

更新面板会自动回发,但您可以使用 AsyncPostBackTrigger 禁用自动回发。将 ChildrenAsTriggers 属性设置为 true,将 UpdateMode 属性设置为 Conditional

<asp:UpdatePanel ID="myPanel" runat="server" ChildrenAsTriggers="true" UpdateMode="Conditional">
<Triggers>        
    <asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />    
</Triggers>  
    <ContentTemplate>
// put your code here to avoid autopost back
    </ContentTemplate>
</asp:UpdatePanel>

另一种禁用自动回发的方法是将 AutoPostBack 设置为 false...

<asp:RadioButtonList ID="RadioButtonList1" AutoPostBack="False">

【讨论】:

    【解决方案2】:

    你需要像这样绑定gridview

    if (!Page.IsPostBack)
    {
       GridView1.DataSource = source;
       GridView1.DataBind();
    }
    

    并尝试。当然它会给你预期的结果。

    【讨论】:

      【解决方案3】:

      尝试在 .
      中使用 CommandArgument='' 属性 它返回所选 GridView 行的索引。
      然后在单击事件上,您可以编写逻辑来获取所选 gridview 行的特定行和列的值。
      例如,如果你想访问第一行的第三列,你可以写 GridView.Rows[0].Cells[2].Text 在click事件或checkedchange事件中取值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多