1

我在通过从数据库中为同一用户获取值来预填充复选框列表时遇到一些问题,需要检查多个复选框。这是一个更新配置文件页面,我希望在此页面加载时根据用户在注册时所做的数据库检查多个复选框。所以,怎么做,我试了很多次,但只有最后一个值被检查,其他都没有被检查。单个用户可以有多个爱好。所以 checkboxlist 是针对爱好的,当更新页面加载时,已经检查了多个爱好,然后他也可以更新和添加更多爱好。更新我已经完成的部分我只希望复选框列表预先填充用户之前给出的所有值。提前致谢。

这是我的 update.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Update.aspx.cs" Inherits="Update" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table class="style1">
        <tr>
            <td class="style3">
                <asp:Label ID="Label2" runat="server" Text="Login Name"></asp:Label>
            </td>
            <td colspan="2">
                <asp:TextBox ID="txtlogin" runat="server" ReadOnly="True"></asp:TextBox>
            </td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td class="style3">
                <asp:Label ID="Label4" runat="server" Text="EmailId"></asp:Label>
            </td>
            <td colspan="2">
                <asp:TextBox ID="txtemail" runat="server" ReadOnly="True"></asp:TextBox>
            </td>
            <td>
                <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" 
                    ControlToValidate="txtemail" Display="Dynamic" ErrorMessage="Invalid" 
                    ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
            </td>
        </tr>
        <tr>
            <td class="style3">
                <asp:Label ID="Label5" runat="server" Text="Address"></asp:Label>
            </td>
            <td colspan="2">
                <asp:TextBox ID="txtadd" runat="server" TextMode="MultiLine" Width="142px" 
                    ReadOnly="True"></asp:TextBox>
            </td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td class="style6">
                <asp:Label ID="Label6" runat="server" Text="City"></asp:Label>
            </td>
            <td colspan="2" class="style7">
                <asp:DropDownList ID="ddlcity" runat="server" Height="21px" Width="142px" 
                    Enabled="False">
                </asp:DropDownList>
            </td>
            <td class="style7">
                &nbsp;</td>
        </tr>
        <tr>
            <td class="style3">
                <asp:Label ID="Label7" runat="server" Text="Pincode"></asp:Label>
            </td>
            <td colspan="2">
                <asp:TextBox ID="txtpin" runat="server" ReadOnly="True" ></asp:TextBox>
            </td>
            <td>
                <asp:RegularExpressionValidator ID="regexpin" runat="server" 
                    ControlToValidate="txtpin" ErrorMessage="Numbers only(six digits)" 
                    ValidationExpression="[0-9]{6}"></asp:RegularExpressionValidator>
            </td>
        </tr>
        <tr>
            <td class="style3">
                <asp:Label ID="Label8" runat="server" Text="PaymentMode"></asp:Label>
            </td>
            <td colspan="2">
                <asp:RadioButtonList ID="rbtnlstpay" runat="server" Height="28px" Width="225px" 
                    Enabled="False">
                </asp:RadioButtonList>
            </td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td class="style3">
                <asp:Label ID="Label9" runat="server" Text="Hobbies"></asp:Label>
            </td>
            <td colspan="2">
                <asp:CheckBoxList ID="cblsthobbies" runat="server" Width="128px" 
                    Enabled="False">
                </asp:CheckBoxList>
            </td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td class="style3">
                &nbsp;</td>
            <td class="style5" colspan="2">
                &nbsp;</td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td class="style3">
                &nbsp;</td>
            <td>
                <asp:Button ID="btnedit" runat="server" Text="Edit" 
                    onclick="btnedit_Click" />
            </td>
            <td>
                &nbsp;</td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td class="style4">
                &nbsp;</td>
            <td class="style2" colspan="2">
                <asp:Label ID="lblresult" runat="server"></asp:Label>
            </td>
            <td class="style2">
            </td>
        </tr>
        <tr>
            <td class="style4">
                &nbsp;</td>
            <td class="style2" colspan="2">
                &nbsp;</td>
            <td class="style2">
                &nbsp;</td>
        </tr>
        <tr>
            <td class="style3">
                &nbsp;</td>
            <td colspan="2">
                &nbsp;</td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td class="style3">
                &nbsp;</td>
            <td colspan="2">
                &nbsp;</td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td class="style3">
                &nbsp;</td>
            <td colspan="2">
                &nbsp;</td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td class="style3">
                &nbsp;</td>
            <td colspan="2">
                &nbsp;</td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td class="style3">
                &nbsp;</td>
            <td colspan="2">
                &nbsp;</td>
            <td>
                &nbsp;</td>
        </tr>
    </table>
    </div>
    </form>
</body>
</html>

这是我的 update.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class Update : System.Web.UI.Page
{
    DataSet ds = new DataSet();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SqlConnection cn = new SqlConnection();
            cn.ConnectionString = @"Data Source=.;Initial Catalog=UserRecords;Integrated Security=True";

            SqlCommand cmd = new SqlCommand();
            cmd.Connection = cn;
            cmd.CommandText = "select * from CityMaster;select * from HobbyMaster;select * from PaymentModeMaster;select * from Users where LoginId = @Loginid;select * from UsersHobbies where LoginId = @Loginid";
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@Loginid",Session["loginid"].ToString());
            cn.Open();
            SqlDataReader dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                ddlcity.Items.Add(new ListItem(dr["CityName"].ToString(), dr["CityId"].ToString()));
            }

            dr.NextResult();

            while (dr.Read())
            {
                cblsthobbies.Items.Add(new ListItem(dr["Hobbyname"].ToString(), dr["HobbyId"].ToString()));
            }

            dr.NextResult();

            while (dr.Read())
            {
                rbtnlstpay.Items.Add(new ListItem(dr["PaymentModename"].ToString(), dr["PaymentModeId"].ToString()));
            }

            dr.NextResult();

            while (dr.Read())
            {
                txtlogin.Text = dr["LoginId"].ToString();
                txtemail.Text = dr["EmailId"].ToString();
                txtadd.Text = dr["Address"].ToString();
                txtpin.Text = dr["Pincode"].ToString();
                ddlcity.SelectedValue = dr["CityId"].ToString();
                rbtnlstpay.SelectedValue = dr["PaymentModeId"].ToString();
            }

            dr.NextResult();

            while (dr.Read())
            {
                for(int i = 0; i < dr.FieldCount; i++)
                {
                    cblsthobbies.SelectedValue = dr["HobbyId"].ToString();
                    //cblsthobbies.SelectedValue = dr.GetValue(1).ToString();
                }
            }
            cn.Close();
        }
    }

    protected void btnedit_Click(object sender, EventArgs e)
    {
        txtemail.ReadOnly = false;
        txtadd.ReadOnly = false;
        ddlcity.Enabled = true;
        txtpin.ReadOnly = false;
        rbtnlstpay.Enabled = true;
        cblsthobbies.Enabled = true;
        btnedit.Text = "Update";
    }
}
4

3 回答 3

2

看起来这是您尝试设置选中状态的地方:

for(int i = 0; i < dr.FieldCount; i++)
{
    cblsthobbies.SelectedValue = dr["HobbyId"].ToString();
    //cblsthobbies.SelectedValue = dr.GetValue(1).ToString();
}

但是,这并不是为CheckBoxList. 这只是SelectedValue为列表本身设置整体。由于只有一个这样的值,循环中的每次迭代都会覆盖前一个值。因此,只剩下最后一个。

为了设置选中状态,您必须为最后一个记录集中的每条记录找到单独的复选框。也许是这样的:

for(int i = 0; i < dr.FieldCount; i++)
{
    cblsthobbies.Items.FindByValue(dr["HobbyId"].ToString()).Selected = true;
}
于 2013-06-28T18:27:18.553 回答
0

循环遍历 cblsthobbies.Items 集合并像这样设置每个项目的 Selected 属性值

foreach (var i in cblsthobbies.Items) 
{
     i.Selected = i.SelectedValue == dr["HobbyId"].ToString();
}
于 2013-06-28T18:24:42.810 回答
0

而不是有两个嵌套循环——一个用于所有可能的选择,然后一个嵌套循环用于在您先前选择的选择中查找每个循环——我喜欢先通读先前选择的选择并将它们存储在一个哈希表中,然后只是遍历 CheckBoxList 中已有的所有项目,如果在 Hashtable 中找到它,则选择一项。这有两个优点:

  • 而不是循环 O(m*n) 次,其中 m 是可能的项目数,n 是先前选择的项目数,它只需要循环 O(m + n) 次(或者我想 O(2m + n ) 计算 CheckBoxList 的构建)
  • 没有嵌套循环,代码看起来更清晰

所以首先我在 .aspx 中独立构建复选框列表

            <asp:SqlDataSource runat="server" ID="dsHobbies"
                SelectCommand="SELECT iHobbyID, sHobbyName FROM tblHobby">
            </asp:SqlDataSource>
            <asp:CheckBoxList runat="server" ID="cblHobbies" DataSourceID="dsHobbies" DataValueField="iHobbyID" DataTextField="sHobbyName "></asp:CheckBoxList>

然后读取先前保存的选择并填充 CheckBoxList 的代码如下所示:

        // read previously chosen items from database
        string sql = "SELECT * FROM tblSelectedHobbies WHERE iPersonID=@pPersonID";
        SqlConnection conn = new SqlConnection();
        conn.ConnectionString = myConnStr;
        conn.Open();
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.Parameters.AddWithValue("pPersonID", id); // id from query string, or wherever
        SqlDataReader reader = cmd.ExecuteReader();

        // iterate through saved entries and add to Hashtable
        Hashtable savedEntries = new Hashtable();
        while (reader.Read())
        {
            string hobbyID= reader["iHobbyID"].ToString();
            savedEntries[hobbyID] = true;
        }
        conn.Close();

        // check the corresponding boxes
        dsHobbies.DataBind();
        cblHobbies.DataBind();
        foreach (ListItem li in cblHobbies.Items)
        {
            if (savedEntries.ContainsKey(li.Value))
            {
                li.Selected = true;
            }
        }
于 2015-08-07T18:57:31.947 回答