在线调查系统的取值问题?or你有更好的思路?
数据库用两个表,一个存调查主题,另一个存对应主题的选项.
显示面页用DataList显示主题,并在ItemTemplate里放了个PlaceHolder用于显示该主题对应的选项,因为调查有单选或多选的可能,所不能直接放RodioButtonList或CheckBoxList. datalist_ItemDataBound事件代码:
protected void dListShowSbject_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
//给调查主题添加编号
if (e.Item.ItemIndex > = 0)
{
((Label)e.Item.FindControl( "lblAutoID ")).Text =Convert.ToString(e.Item.ItemIndex + 1);
}
//邦定对应调查主题的选项
int pollid = int.Parse(this.dListShowSbject.DataKeys[e.Item.ItemIndex].ToString());
string selectMode = pl().GetPollSelectMode(pollid).ToString();//取得选择模式(selectmode)
RadioButtonList rbl = new RadioButtonList();
rbl.DataSource = pl().GetPollOptions(pollid);
rbl.DataValueField = "id ";
rbl.DataTextField = "options ";
CheckBoxList cbl = new CheckBoxList();
cbl.DataSource = pl().GetPollOptions(pollid);
cbl.DataValueField = "id ";
cbl.DataTextField = "options ";
PlaceHolder pollHolder = (PlaceHolder)e.Item.FindControl( "pollHolder ");
if (selectMode == "1 ")//判断是否是单选
{
rbl.DataBind();
pollHolder.Controls.Add(rbl);//RadioButtonList绑定
}
else
{
cbl.DataBind();
pollHolder.Controls.Add(cbl);//CheckBoxList绑定
}
}
}
显示没有问题
取值:我是在一个button里用循环来取值的,但是报错了,
代码:
protected void btnSubmit_Click(object sender, EventArgs e)
{
for (int i = 0; i < this.dListShowSbject.Items.Count; i++)
{
int pollid = int.Parse(this.dListShowSbject.DataKeys[i].ToString());
string selectMode = pl().GetPollSelectMode(pollid).ToString();//取得选择模式(selectmode)
if (selectMode == "1 ")
{
RadioButtonList rbl = ((RadioButtonList)(this.dListShowSbject.Items[i].FindControl( "pollHolder ").Controls[0]));
int opid = int.Parse(rbl.SelectedValue);
Response.Write(opid);//测试能否取到值
}
else
{
CheckBoxList cbl = (CheckBoxList)(this.dListShowSbject.Items[i].FindControl( "pollHolder ").Controls[0]);
string opid = " ";
for (int j = 0; j < cbl.Items.Count; i++)
{
if (cbl.Items[j].Selected)
{
opid += cbl.Items[j].Value + ", ";
}
if (opid != string.Empty)
{
Response.Write(opid);//测试能否取到值
}
}
}
}
}
错误提示:指定的参数已超出有效值的范围。
参数名: index
红色代码:RadioButtonList rbl = ((RadioButtonList)(this.dListShowSbject.Items[i].FindControl( "pollHolder ").Controls[0]));
找了半天的错了,我自己测了一下,发现如果是静态在PlaceHolder放的控件就能找到,但在代码添加的到PlaceHolder的控件就提示超出范围.
请各位大哥帮忙看看,或者你们有好的思路也讲讲,先谢谢了,在线等候...
[解决办法]
因為提交后dListShowSbject重綁定不會產生動態添加的控件﹐所以取不到。
可以考慮用一個隱藏域﹐在客戶端選取時﹐保存選取的內容。
[解决办法]
学习,
帮顶
[解决办法]
你的最终目的是想获取客户选择了那一个值
问题是pollHolder.Controls.Add()方法时没有动态加入你的指定子控件
由于你的btnSubmit的按钮不是DataList控件的子控件,我不清楚你的DataList的Binding在什么时候被引发的,但可以知道在Click事件下不会引发DataList的ItemdataBound事件,不会执行pollHolder.Controls.Add()这些代码,click事件之前只会Load你的原始状态, 动态的控件就不会被加入到pollHolder中去;
方法很多,最直接的方法就是:把你的BtnSubmit放到DataList中,代码就不用改太多了
具体做法我就不说了
[解决办法]
你现在是要后台添加调查的问题,还是显示出来让客户去选阿?
你好像是后者的显示:我的思路是这样的;
后台添加的时候就确定类型:多选还是单选,然后在前台根据类型来考虑是否什么控件;
这样的话你不要动态的写,直接放在panel里面隐藏和显示好了;
这些经验都是在线测试做的时候得思路,应该对你有所帮助!