将SQL数据库中选定的GridView值分配给变量
本文关键字:GridView 分配 变量 SQL 数据库 | 更新日期: 2025-04-15 20:13:57
我正在尝试将GridView控件中的值分配给会话变量。我有一个SQL数据库,其中有一个名为Computer_Cases的表,还有一个称为FormFactor的列。我的GridView名为GridView1,SqlDataSource为:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:HardwareConnectionString %>"
SelectCommand="SELECT * FROM [Computer_Cases]"></asp:SqlDataSource>
很明显,GridView只是显示案例表中的所有内容。我在GridView控件上启用了选择,但当有人选择一行时,我不知道如何将值实际保存到变量(例如Session["Form_Factor_Selection_Variable"])。我正在尝试将所选行的FormFactor列的值存储在GridView控件上。然后,该值将在另一个页面上用于显示形状因子与最初选择的形状因子匹配的所有主板(不同的表)。

您必须使用GridView的SelectedIndexChanged事件。下面是一个例子。
void YourGridView_SelectedIndexChanged(Object sender, GridViewSelectEventArgs e)
{
GridViewRow row = YourGridView.SelectedRow;
Session["Form_Factor_Selection_Variable"] = row.Cells[1].Text; // use the proper index for the cell that you want to save in session variable
}
并且,确保在GridView 的标记代码中添加以下属性
onselectedindexchanged="YourGridView_SelectedIndexChanged"