我有web应用程序,其中我使用gridview。在gridview中,我使用了radiobutton列表,这个radiobutton列表有两个项Yes
和No
。我想从这两个中选择一个项取决于我在绑定时从数据集获得的值。假设我的列名是is_selected
并返回True
,然后应检查单选按钮列表Yes
。
这是我自己尝试但没有成功的代码,
<asp:TemplateField HeaderText="Ready To Join?" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:RadioButtonList ID="rbd_join" AutoPostBack="true" runat="server"
RepeatDirection="Horizontal" BorderStyle="None" BorderWidth="0px" BorderColor="Transparent"
onselectedindexchanged="rbd_join_SelectedIndexChanged"
DataValueField="is_selected">
<asp:ListItem Text="Yes" Value="1" ></asp:ListItem>
<asp:ListItem Text="No" Value="0"></asp:ListItem>
</asp:RadioButtonList>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
编辑后
加成
.cs文件 按钮点击事件这是代码:
Dataset ds=new Dataset();
ds=bindgrid();
if(ds.table[0].rows.count>0)
{
grd_view.Datasource=ds.tables[0];
grd_view.Databind();
}
public Dataset bindgrid()
{
SqlParameter stud_ID = new SqlParameter("@student_id", SqlDbType.Int);
stud_ID.Value = 1;
SqlCommand cmdSql = new SqlCommand();
cmdSql.CommandType = CommandType.StoredProcedure;
cmdSql.CommandText = "usp_select_candidate_inplacement_byAdmin";
cmdSql.Parameters.Add(stud_ID);
DataSet ds = new DataSet();
DataClass dl = new DataClass();
ds = dl.dsSelect(cmdSql);
return ds;
}
这是我添加的事件
protected void grd_view_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var radioList = e.Row.FindControl("rbd_join") as RadioButtonList;
var myobject = e.Row.DataItem as DataRow;
bool is_sel = bool.Parse(myobject ["is_selected"].ToString());
radioList.SelectedValue = is_sel ? "1" : "0";
}
}
答案 0 :(得分:2)
您需要使用RowDataBound
事件:
<asp:GridView ..... OnRowDataBound="gv_RowDataBound"
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var radioList = e.Row.FindControl("rbd_join") as RadioButtonList;
// this will be the object that you are binding to the grid
var myObject = e.Row.DataItem as DataRowView;
bool isSelected = bool.Parse(myObject["is_selected"].ToString());
radioList.SelectedValue = isSelected ? "1" : "0";
}
}