【发布时间】:2016-08-17 00:42:46
【问题描述】:
我有一个函数可以检查需要执行哪个 sql 查询并返回一个 DataTable,它被称为 searchData,位于 CarsDataSet 类中
DataTable dataTable = null; //before there is code to detect the sql command to execute
if (sqlCommand != null)
{
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand, con);
dataTable = new DataTable();
sqlDataAdapter.Fill(dataTable);
}
return dataTable;
然后,我在 aspx.cs 页面上使用此函数,以便将此 DataTable 绑定到 GridView..
GridViewCarsFiltered.DataSource = carsDataSet.searchData(type, manufacturer, maxPrice, minPrice, maxYear, minYear);
GridViewCarsFiltered.DataBind();
GridView 被正常填充,但是当尝试使用选择索引更改处理程序获取行的值时出现问题。..
protected void GridViewCarsFiltered_SelectedIndexChanged(object sender, EventArgs e)
{
string carId = GridViewCarsFiltered.SelectedRow.Cells[1].Text;
}
我收到 'ArgumentOutOfRangeException' 说 carId 为空。
这是我的 GridView,DataSourceID 为空,因为我是从后面的代码中设置的。
<asp:GridView ID="GridViewCarsFiltered" runat="server" CssClass="table table-striped table-hover" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" DataSourceID="" ForeColor="Black" OnSelectedIndexChanged="GridViewCarsFiltered_SelectedIndexChanged" DataKeyNames="Id">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False" ReadOnly="True" SortExpression="Id" />
<asp:BoundField DataField="type" HeaderText="type" SortExpression="type" />
<asp:BoundField DataField="manufacturer" HeaderText="manufacturer" SortExpression="manufacturer" />
<asp:BoundField DataField="model " HeaderText="model " SortExpression="model " />
<asp:BoundField DataField="colour" HeaderText="colour" SortExpression="colour" />
<asp:BoundField DataField="price" HeaderText="price" SortExpression="price" />
<asp:BoundField DataField="year" HeaderText="year" SortExpression="year" />
<asp:BoundField DataField="location" HeaderText="location" SortExpression="location" />
<asp:BoundField DataField="username" HeaderText="username" SortExpression="username" />
</Columns>
</asp:GridView>
这是实际填充的 GridView 的屏幕截图
我希望我已经足够清楚,并且你们中的一些人可以帮助我...... 提前谢谢你
【问题讨论】:
-
您确定索引
1(使其成为第二列)处的Cells正在被填充吗? -
是的,我填充了更多的单元格,我没有上传我的代码,因为我的代码不相关。如果我注释掉第一个单元格的代码,我将遇到同样的问题来检索第二个单元格..已经尝试过了!
-
你可以试试 GridViewRow row =GridViewCarsFiltered.Rows[e.NewSelectedIndex];字符串 carId=row.Cells[1].Text;
-
同样的事情,不工作。我一直在以不同的形式使用相同的事件处理程序,它工作正常,它可以正确检测行中的字段。
-
你能发布你的 GridView 的标记吗?正如@khlr 所建议的,问题似乎来自
Cells[1]。
标签: c# asp.net visual-studio gridview