【发布时间】:2013-01-24 21:08:40
【问题描述】:
所以基本上,我的目标是做一个简单的循环,在提交时检查是否有一堆框在继续之前被选中。我知道如何在 PHP 或 MVC 中做到这一点,但我的老板强迫我使用 web 控件。
所以,我们到了。
Default.aspx中的相关代码
<div>
<asp:CheckBoxList id="eligibilityreqs" runat="server">
<asp:ListItem value="item1" runat="server">I am great</asp:ListItem>
<asp:ListItem value="item2" runat="server">I am amazing.</asp:ListItem>
<asp:ListItem value="item3" runat="server">I completed EVERTHING</asp:ListItem>
<asp:ListItem value="item4" runat="server">Pies are delicious</asp:ListItem>
<asp:ListItem value="item5" runat="server">Oh man a fifth one</asp:ListItem>
</asp:CheckBoxList>
</div>
<p>
<asp:Label Text="" id="finalmessage" runat="server" />
</p>
<div>
<asp:Button Text="Submit" runat="server" onclick="process" />
</div>
Default.aspx 的代码隐藏
using System;
using System.Web;
using System.Web.UI;
using System.Data;
using System.Web.Configuration;
using System.Data.Odbc;
using System.Web.UI.WebControls;
namespace minor
{
public partial class Default : System.Web.UI.Page
{
protected void process (object sender, EventArgs e)
{
bool valid = true;
string debugtext = "";
foreach (ListItem li in eligibilityreqs.Items) {
if (!li.Selected) {
valid = false;
debugtext = debugtext + li.Selected;
}
}
if (!valid) {
finalmessage.Text = "There has been an error, please check all boxes." + debugtext;
} else {
string conString = WebConfigurationManager.ConnectionStrings ["connectionstring"].ConnectionString;
using (OdbcConnection con = new OdbcConnection(conString)) {
string sqlstring = "SELECT yum FROM pie_application LIMIT 1;";
using (OdbcCommand com = new OdbcCommand(sqlstring, con)) {
con.Open ();
string reader = Convert.ToString (com.ExecuteScalar ());
finalmessage.Text = reader;
}
}
}
}
}
}
debugtext 的输出仅供参考,假,假,假,假,假。
【问题讨论】:
-
您如何、何时以及从何处对
CheckBoxList进行数据绑定? -
Lani,你能在
bool valid = true上方添加这一行,但在这一行之后添加一个断点,然后检查你是否得到一个已检查项目的列表?List<ListItem> items = eligibilityreqs.Items.Cast<ListItem>().Where(n => n.Selected).ToList(); -
我刚刚注意到另一个潜在问题,我会将
string reader = Convert.ToString (com.ExecuteScalar ());更改为var reader = (string)com.ExecuteScalar();
标签: c# web-controls checkboxlist listitem asp.net-webcontrol