背景信息:
由于各种原因,我不得不在GridView的一列中动态创建一个GridView。
网格向用户提供了一组数据,用户必须在这些数据上留下评论,并就三种无线电选项中的一种做出决定:

当然,网格上有许多行。它的工作方式是用户在保存到数据库之前,对进行评论和决策,所有的都是项目。
此屏幕将多次使用,因此单选按钮必须反映存储在数据库中的值。
问题:
除了一件事之外,所有的事情都是工作的:单选按钮总是被重置到它们的初始状态(value = 1),因为网格和控件是在回发时重新创建的。
代码:
这是工作代码,其中一些是编辑的.
protected void TheGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
[...]
foreach (DataControlFieldCell dc in e.Row.Cells)
{
switch (dc.ContainingField.ToString())
{
[...]
case (_ColReview):
int status = int.Parse(dc.Text);
if (status == 0)
{
dc.Text = "Not sent for review";
}
else
{
var comment = new TextBox();
comment.ID = "ReviewCommentTextBox";
comment.CssClass = "form-control";
comment.Width = 290;
dc.Controls.Add(comment);
var radioButtons = new RadioButtonList();
var rb = new ListItem();
if (status == 2) rb.Selected = true;
rb.Value = "2";
rb.Text = "Yes, Add to Watch List";
radioButtons.Items.Add(rb);
rb = new ListItem();
if (status == 3) rb.Selected = true;
rb.Value = "3";
rb.Text = "No, do not add to Watch List";
radioButtons.Items.Add(rb);
rb = new ListItem();
//initial value in database is 1, hence this will be initially selected
if (status == 1) rb.Selected = true;
rb.Value = "1";
rb.Text = "Skip: no decision";
radioButtons.ID = "RowRadioButtonList";
radioButtons.Items.Add(rb);
dc.Controls.Add(radioButtons);
}
break;
}
}
}
}
protected void BulkupdateLinkButton_Click(object sender, EventArgs e)
{
foreach(GridViewRow gvr in TheGridView.Rows)
{
[...]
int radioItemValue = 0;
foreach (DataControlFieldCell dc in gvr.Cells)
{
string cellName = dc.ContainingField.ToString();
string cellText = dc.Text;
switch(cellName)
{
[...]
case (_ColReview):
TextBox tb = (TextBox)gvr.FindControl("ReviewCommentTextBox");
comment = tb.Text;
RadioButtonList rbl = (RadioButtonList)gvr.FindControl("RowRadioButtonList");
foreach(ListItem li in rbl.Items)
{
//Issue arrives here: selected item is reset on postback, value is always 1
if (li.Selected)
{
radioItemValue = ToolBox.ConvertToInt(li.Value);
}
}
break;
}
}
if (!string.IsNullOrEmpty(comment) && (radioItemValue > 0))
{
if (radioItemValue != 1) // 1 = pending/skip
{
//code to add update the record and save the comment
[...]
}
}
}
}关于解决的想法
现在,我可以通过在每一行中使用一个HiddenField并设置一些JavaScript/JQuery来记录所选的RadioButton来解决这个问题,但是我不得不认为我在这里遗漏了一个技巧?有人能提供更好的解决方案吗?
发布于 2015-02-16 13:54:15
要将RadioButtonList.SelectedIndex还原到已保存的选定值,我认为需要设置列表的RadioButtonList属性,而不是ListItem的选定属性
https://stackoverflow.com/questions/28371098
复制相似问题