[英]Selected Index Changed return null values on a populated Grid View
我有一個檢查需要執行哪個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為null。
這是我的GridView,DataSourceID為null,因為我是在后面的代碼中進行設置的。
<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的屏幕截圖
我希望我已經足夠清楚,希望你們中的一些人能幫助我...預先謝謝
在這種情況下,檢索值的首選方法是使用DataKeyNames
而不是從單元格本身獲取值。 此方法還可用於從GridView列中未顯示的字段中獲取值。
您可以將Id
字段添加到標記中的該屬性:
<asp:GridView ID="gv" runat="server" DataKeyNames="Id" ... >
並以這種方式在代碼背后檢索值:
protected void gv_SelectedIndexChanged(object sender, EventArgs e)
{
int carId = (int)gv.DataKeys[gv.SelectedRow.RowIndex].Values["Id"];
}
注意:我使用gv
而不是GridViewCarsFiltered
只是為了減小代碼樣本的寬度。
更新
另一方面,如果在選擇行之后GridView為空,則問題可能是ViewState被禁用(在頁面級別或Web.config中)。 啟用它可以解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.