0

我有使用gridview 的Web 应用程序。在gridview中我使用了单选按钮列表这个单选按钮列表有两个项目。我想从这两个项目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";

            }
}
4

1 回答 1

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";
    }
}
于 2012-07-19T08:26:55.210 回答