【问题标题】:How do I select a checkbox bound to a checkbox control from within c# code?如何从 c# 代码中选择绑定到复选框控件的复选框?
【发布时间】:2017-12-07 04:41:42
【问题描述】:
 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";
        }

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

我知道您只需要一个复选框即可使用checkbox.checked = true。我在我的代码中可以正常工作,但我需要在控件中将复选框链接在一起,以便我可以根据用户是否更改其中的任何一个来触发事件。

为了提供一点背景知识,我从 SQL 数据库中提取数据并通过 WebForm 输出到用户界面。

【问题讨论】:

  • 您的意思是带有OnSelectedIndexChanged 事件的CheckBoxList 控件?根据您的(有些不清楚的)描述,这似乎是您需要的。
  • 对不起,我不够清楚。谢谢回复。不,我不是要根据像 OnSelectedIndexChanged 这样的事件来更改它,而是根据我从 SQL 数据库中提取的数据来更改它。例如,如果数据库中的数据 == "Clinic",则需要选中 BillingEntityCheckbox 控件中的 Clinic 复选框。

标签: c# asp.net checkbox webforms


【解决方案1】:

我认为您缺少数据绑定的概念,这是您要寻找的吗?:

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;
        }
    }
}

^“背后的代码”

<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" />

^网络表单 xml

希望对您有所帮助!

附言我认为在BillingEntity 类型上创建一个readonly property 是个好主意,这将返回一个布尔值,用于检查该类中的"clinic",使其更加面向对象..

【讨论】:

  • 谢谢。我没有使用过数据绑定,但这看起来像是我一直缺少的。感谢您的帮助!
猜你喜欢
  • 2018-03-19
  • 1970-01-01
  • 2018-11-22
  • 2014-10-07
  • 1970-01-01
  • 2010-10-19
  • 2021-04-11
  • 1970-01-01
  • 2016-06-13
相关资源
最近更新 更多