在尝试从gridview中的单元格中获取值时,我遇到了困难。每当我要求它进入NullExcaption的值时,我就会询问该行本身是否为null,它是。这是ASP代码:
<asp:SqlDataSource ID="SqlDataSourceFlats" runat="server" ConnectionString="<%$ ConnectionStrings:EflatsConnectionString %>" SelectCommand="SELECT [Rent], [Address], [FlatId] FROM [Flat_Main]"></asp:SqlDataSource>
<asp:GridView ID="GridView1" onrowcommand="GridView1_RowCommand" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="FlatId" DataSourceID="SqlDataSourceFlats" ForeColor="#333333" GridLines="None" Width="100%" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="FlatId" HeaderText="FlatId" InsertVisible="False" ReadOnly="True" SortExpression="FlatId" />
<asp:BoundField DataField="Rent" HeaderText="Rent" SortExpression="Rent" />
<asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address">
<ControlStyle Width="60%" />
</asp:BoundField>
<asp:ButtonField Text="Add" CommandName="Apply" ButtonType="Button" />
<asp:ButtonField Text="Remove" ButtonType="Button" />
</Columns>
<EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>
按钮代码:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Apply")
{
// string c = GridView1.Rows[e.NewEditIndex].Cells[2].Text;
// Response.Write(GridView1.SelectedRow.Cells[2].Text);
if (GridView1.SelectedRow == null)
{
Response.Write("Gridview is failing me :(");
}
// string celltext = this.GridView1.SelectedRow.Cells[2].Text;
// Response.Write(celltext);
}
}
基本上我想点击按钮并从所选行中获取FlatId值。
答案 0 :(得分:1)
OnRowCommand事件似乎没什么错误。
1。)GridView1.SelectedRow
::
您实际上没有选择任何行,因此总是null
2。)GridView1.Rows[e.NewEditIndex]
::
同样,您不是在编辑任何行,那么您期望e.NewEditIndex
的值是什么?
如何处理GridView控件中的ButtonField事件
CommandName
属性设置为标识其功能的字符串,例如“选择”,“编辑”等... CommandArgument
属性。 ButtonField
类使用适当的行索引值自动填充CommandArgument
属性。以下是选择记录和处理OnRowCommand
事件的示例:
标记:
<columns>
<asp:buttonfield buttontype="Button" commandname="Select"
headertext="Select This Record" text="Select"/>
</columns>
和OnRowCommand
事件:
void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Select")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int _rowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = CustomersGridView.Rows[_rowIndex];
string cellText = selectedRow.Cells[2].Text;
}
}