如何从c#代码中选择绑定到复选框控件的复选框?

时间:2017-07-03 20:38:46

标签: c# asp.net checkbox webforms

$data['albums']

如何从基础代码中检查复选框列表中的项目?

我知道只使用一个复选框 BillingEntity = (string)rdr["BillingEntity"]; string[] split = BillingEntity.Split(','); for (int i = 0; i < split.Length; i++) { split[i] = split[i].Trim(); if (split[i] == "Clinic") { BillingEntityCheckBox.Items[i].Checked = true; Session["billingEntitySessionVar"] = Session["billingEntitySessionVar"] + " Clinic"; } 。我在我的代码中工作正常,但是我需要在控件中将复选框链接在一起,以便我可以根据用户是否更改过任何事件来触发事件。

为了给一点背景知识,我从SQL数据库中提取数据并通过checkbox.checked = true输出到用户界面。

1 个答案:

答案 0 :(得分:0)

我认为您错过了数据绑定的概念,这是您正在寻找的内容吗?:

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string[] myStrings = new string[] { "Example Value", "Not a Thing", "Many Things", "All the Thing" };
        cblThingy.DataSource = myStrings;
        cblThingy.DataBind();
    }

    protected void btnPushMe_Click(object sender, EventArgs e)
    {
        //for all the things
        foreach(ListItem itemThing in cblThingy.Items)
        {
            //set a default of not selected
            itemThing.Selected = false;

            //if the text is the same
            //you can have any check you like here
            if (itemThing.Text == txtThing.Text)

                //say that it's selected
                itemThing.Selected = true;
        }
    }
}

^&#34;背后的代码&#34;

<asp:Label ID="lblThing" runat="server" Text="If you type the text and push the button the thing with select." />

<asp:TextBox ID="txtThing" runat="server" Text="Example Value" />

<asp:Button ID="btnPushMe" runat="server" Text="Push My Button" OnClick="btnPushMe_Click" />

<asp:CheckBoxList ID="cblThingy" runat="server" />

^ webform xml

希望这有帮助!

P.S。我认为在readonly property类型上创建一个BillingEntity是一个好主意,它会返回一个bool,它会检查该类中的"clinic",使其更加面向对象。