如何在gridview中选择单选按钮取决于数据集的值返回?

时间:2012-07-19 08:18:16

标签: asp.net gridview dataset radiobuttonlist

我有web应用程序,其中我使用gridview。在gridview中,我使用了radiobutton列表,这个radiobutton列表有两个项YesNo。我想从这两个中选择一个项取决于我在绑定时从数据集获得的值。假设我的列名是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";

            }
}

1 个答案:

答案 0 :(得分:2)

您需要使用RowDataBound事件:

ASPX

<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";
    }
}