我在 asp.net 中有一个 gridview,并且在表中我有两列。 现在,我必须在按钮单击时以 dllDesc 和 txtBoxDesc 字段警报的形式逐行显示列索引值。
<asp:GridView ID="gvCar" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" AutoGenerateColumns="False" DataKeyNames="LevelID" OnRowDataBound="gvCar_RowDataBound">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Car">
<ItemTemplate>
<asp:Label ID="Car" runat="server" Width="150px" Height="30px" Font-Names="Georgia" MyCustomAttr="foo" margin-Left="100px" Text='<%# Bind("CharName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:DropDownList ID="ddlDesc" Width="142px" Height="35px" Font-Names="Georgia" margin-Left="100px" runat="server">
</asp:DropDownList>
<asp:TextBox ID="txtBoxDesc" runat="server" Width="130px" Height="28px" Font-Names="Georgia" margin-Left="100px" Text=''></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
我设法获取行的值(下面的代码),但我找不到一种方法来显示列的值。
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvr in gvCar.Rows)
{
string PrimaryKey = gvCar.DataKeys[gvr.RowIndex].Values[0].ToString();
MessageBox.Show(PrimaryKey);
}
}
有人可以帮我吗?
最佳答案
只需在 GridView 上像这样绑定(bind)它,不需要做任何其他事情
<asp:TemplateField HeaderText="No.">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
编辑更新2
只需添加选定的索引更改事件
<asp:GridView ID="gvCar" runat="server" OnSelectedIndexChanged="gvCar_SelectedIndexChanged">
在你的cs文件中
protected void gvCar_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
string a = gvCar.SelectedRow.Cells[0].Text; //Write here that cell index of index no
}
catch (Exception ex)
{
}
}
如果您想通过行命令执行此操作,请打开以下链接
这对你有用
关于asp.net - 获取gridview中的列索引值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50405003/