You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET如何将GridView每行下拉选择值与对应学院ID存入数据库

第一步:先修正GridView配置

你当前给GridView设置了EnableViewState="False",会导致页面回发提交时丢失行数据和下拉框选中状态,首先修改这个属性为True:

<asp:GridView ID="gdvAcadSelec" runat="server" AutoGenerateColumns="False"
    DataKeyNames="acad_Id" DataSourceID="srcAcademy"
    OnRowDataBound="gdvAcadSelec_RowDataBound"
    CssClass="table table-striped table-bordered"
    EnableViewState="True">
<!-- 其余列代码保持不变 -->
</asp:GridView>

第二步:完善提交按钮逻辑

提交逻辑的核心流程:

  • 校验当前登录学生的Session有效性
  • 遍历GridView的所有数据行,跳过表头、表尾行
  • 查找每行的下拉框,跳过未选择优先级的行,可额外校验是否存在重复优先级
  • 从DataKeys集合中获取当前行对应的学院ID
  • 将学院ID、学生ID、优先级三个字段插入tblAcademySelection表

完整的btnsubmit_Click代码如下:

protected void btnsubmit_Click(object sender, EventArgs e)
{
    // 校验登录状态,获取学生ID
    if (Session["stud_id"] == null || !int.TryParse(Session["stud_id"].ToString(), out int studId))
    {
        ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('请先登录后再提交');", true);
        return;
    }

    // 用于校验优先级是否重复,可根据需求删除
    HashSet<int> usedPreference = new HashSet<int>();

    foreach (GridViewRow row in gdvAcadSelec.Rows)
    {
        // 仅处理数据行
        if (row.RowType != DataControlRowType.DataRow) continue;

        // 查找当前行的下拉框控件
        DropDownList ddlPref = row.FindControl("ddlPref") as DropDownList;
        if (ddlPref == null) continue;

        // 跳过未选择优先级的行(下拉框第一项是"Please select")
        if (ddlPref.SelectedIndex == 0 || !int.TryParse(ddlPref.SelectedValue, out int preference))
        {
            continue;
        }

        // 优先级重复校验,可根据需求删除
        if (usedPreference.Contains(preference))
        {
            ClientScript.RegisterStartupScript(this.GetType(), "alert", $"alert('优先级{preference}重复选择,请修改后再提交');", true);
            return;
        }
        usedPreference.Add(preference);

        // 获取当前行绑定的学院ID(来自DataKey)
        int acadId = Convert.ToInt32(gdvAcadSelec.DataKeys[row.RowIndex].Value);

        // 操作数据库插入数据,示例为原生ADO.NET写法,注意用参数化查询避免SQL注入
        string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["你的连接字符串节点名"].ConnectionString;
        using (SqlConnection conn = new SqlConnection(connStr))
        {
            string insertSql = @"INSERT INTO tblAcademySelection (acad_id, stud_id, order_of_preference) 
                                 VALUES (@acadId, @studId, @preference)";
            using (SqlCommand cmd = new SqlCommand(insertSql, conn))
            {
                cmd.Parameters.AddWithValue("@acadId", acadId);
                cmd.Parameters.AddWithValue("@studId", studId);
                cmd.Parameters.AddWithValue("@preference", preference);
                conn.Open();
                cmd.ExecuteNonQuery();
            }
        }

        // 如果你要复用现有dataAccessLayer,直接调用对应插入方法即可,示例:
        // dataAccessLayer.InsertAcademySelection(acadId, studId, preference);
    }

    ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('志愿提交成功');", true);
}

补充说明

  • 如果需要支持修改已提交的志愿,可以在插入前先判断当前学生的该学院选择是否已存在,存在就执行UPDATE,不存在才执行INSERT
  • 建议把数据库连接字符串放在web.config的connectionStrings节点中,不要硬编码在业务代码里
  • 如果需要保证所有数据同时插入成功,可以给整个插入逻辑加事务,避免部分成功部分失败的异常情况

内容的提问来源于stack exchange,提问作者DeathStriker2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 10:15:04