gridview绑定linqdatasource后获取gridview中的字段

这篇博客介绍了如何在ASP.NET中,当GridView绑定到LINQDataSource后,获取GridView中特定字段的方法。通过在Button点击事件中遍历GridView的行,查找CheckBox并判断其状态,从而获取对应行的ThemeId。示例代码展示了如何在CheckBox被选中时,将ThemeId显示在Label上。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于如何从绑定数据源控件的gridview查询的结果中获取其中的一个字段,网上找了很多方法,这是本人最终的解决办法

界面设计:

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="find" runat="server" OnClick="find_Click" Text="find" />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ThemeId" DataSourceID="LinqDataSource1" OnRowDataBound="GridView1_RowDataBound">
            <Columns>
                <asp:BoundField DataField="ThemeId" HeaderText="ThemeId" InsertVisible="False" ReadOnly="True" SortExpression="ThemeId" />
                <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                <asp:BoundField DataField="Context" HeaderText="Context" SortExpression="Context" />
                <asp:CheckBoxField DataField="Screen" HeaderText="Screen" SortExpression="Screen" />
                <asp:CommandField HeaderText="编辑" ShowEditButton="True" />
                <asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
                <asp:TemplateField HeaderText="获取id">
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBox2" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:LinqDataSource ID="LinqDataSource1" runat="server" ContextTypeName="CardDataContext" EntityTypeName="" TableName="Theme" EnableUpdate="True" EnableDelete="True" Where="ThemeId == @ThemeId">
            <WhereParameters>
                <asp:Parameter DefaultValue="3" Name="ThemeId" Type="Int32" />
            </WhereParameters>
        </asp:LinqDataSource>
        <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>

        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" style="height: 21px" Text="确定" />


先选定获取id列中的checkbok然后点击确定按钮后在label中会获取本行的ThemeId的值

具体的方法代码如下:

 protected void Button1_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow gvRow in GridView1.Rows)
        {
            //id = (Label)gvRow.FindControl("Label1");
            //((Label)(GridView1.Rows[e.RowIndex].Cells[8].Controls[0])).Text.ToString().Trim();
            CheckBox CheckBox2 = (CheckBox)gvRow.FindControl("CheckBox2");//FindControl(String)使用指定的服务器控件当前命名容器中搜索 id 参数。
            if (CheckBox2.Checked)
            {
                Label2.Text = gvRow.Cells[0].Text;
            }
        }
    }

这样就能获取gridview中查询的数据的字段了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值