我使用的是GridView
,其中有四列:labelID
,fName
,lName
和Grade
。 Grade
是简单的通过或失败Radiobuttonlist
。一旦数据更新,我希望它在下次重新加载时拉取数据,以在用户通过或失败时显示所选值。这是代码:
<asp:TemplateField>
<ItemTemplate>
<asp:RadioButtonList ID="rblChoices" runat="server" OnSelectedIndexChanged="rblChoices_SelectedIndexChanged" Text='<%# Eval("Grade") %>'>
<asp:ListItem Value="Pass" Text="Pass"></asp:ListItem>
<asp:ListItem Value="Fail" Text="Fail"></asp:ListItem>
</asp:RadioButtonList>
</ItemTemplate>
</asp:TemplateField>
C#代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
private void BindData()
{
string connectiongString = "Data Source=WSCJTCSQ1;Initial Catalog=LiquorStore;Integrated Security=True";
SqlConnection myConnection = new SqlConnection(connectiongString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT id, firstname, lastname, nickname, Grade FROM Company", myConnection);
DataSet ds = new DataSet();
ad.Fill(ds);
gvUsers.DataSource = ds;
gvUsers.DataBind();
}
提前谢谢!
答案 0 :(得分:2)
您必须为此
使用GridView RowDataBound事件<强> HTML 强>
<asp:GridView runat="server" ID="gvUsers" OnRowDataBound="gvUsers_RowDataBound" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%# Eval("Name") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:RadioButtonList ID="rblChoices" runat="server">
<asp:ListItem Value="Pass" Text="Pass"></asp:ListItem>
<asp:ListItem Value="Fail" Text="Fail"></asp:ListItem>
</asp:RadioButtonList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
C#代码
一个非常简单的公司类 - Company.cs
public class Company
{
public string Name { get; set; }
public string Grade { get; set; }
}
<强> .aspx.cs 强>
protected void Page_Load(object sender, EventArgs e)
{
List<Company> companies = new List<Company>()
{
new Company(){ Name = "Toyota", Grade = "Pass"},
new Company(){ Name = "Form", Grade = "Fail"}
};
gvUsers.DataSource = companies;
gvUsers.DataBind();
}
protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.DataItem != null)
{
string grade = DataBinder.Eval(e.Row.DataItem, "Grade") as string;
if (!string.IsNullOrEmpty(grade))
{
RadioButtonList radio = e.Row.FindControl("rblChoices") as RadioButtonList;
radio.Items.FindByValue(grade).Selected = true;
//You can use this to select as well - see comments from Andomar
//radio.SelectedValue = grade;
}
}
}
}
<强>输出强>