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

如何将Repeater控件中选中的RadioButton值插入SQL数据库

实现选中RadioButton值插入SQL数据库的完整方案

后端按钮点击事件处理逻辑

在后台的Button3_Click方法中,遍历Repeater的所有行拿到选中项的值,再执行数据库插入操作,参考代码如下:

protected void Button3_Click(object sender, EventArgs e)
{
    string selectedAddressName = string.Empty;
    // 如果需要存储地址ID,建议在ItemTemplate中新增隐藏字段存储对应ID
    // int selectedAddressId = 0;

    // 遍历Repeater所有行
    foreach (RepeaterItem item in ManageAddressRepeater.Items)
    {
        RadioButton rb = item.FindControl("RadioButton1") as RadioButton;
        if (rb != null && rb.Checked)
        {
            selectedAddressName = rb.Text;
            // 取隐藏字段ID逻辑示例:HiddenField hfId = item.FindControl("hfAddressId") as HiddenField; selectedAddressId = Convert.ToInt32(hfId.Value);
            break;
        }
    }

    // 未选中时的拦截逻辑
    if(string.IsNullOrEmpty(selectedAddressName))
    {
        // 可自行添加未选择提示,例:ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('请先选择地址');", true);
        return;
    }

    // 参数化查询插入数据库,避免SQL注入风险
    string connectionString = "替换为你的数据库连接字符串";
    string insertSql = "INSERT INTO 目标表名 (对应存储字段名) VALUES (@AddressName)";
    // 需要存ID的话自行修改SQL语句和参数即可
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        using(SqlCommand cmd = new SqlCommand(insertSql, conn))
        {
            cmd.Parameters.AddWithValue("@AddressName", selectedAddressName);
            conn.Open();
            cmd.ExecuteNonQuery();
        }
    }
    // 插入成功后的后续逻辑,如操作提示、页面跳转等自行补充
}

可选优化:简化单选逻辑

无需手写JavaScript实现单选,直接给RadioButton设置GroupName属性即可实现原生单选,修改前端RadioButton代码如下:

<asp:RadioButton ID="RadioButton1" runat="server" Text='<%#Eval("Name") %>' GroupName="AddressSelection" />

修改后可删除现有单选JS代码,运行效果和之前一致,稳定性更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 18:15:04