2012-10-25 62 views
-1

我正在構建項目,並且正在創建動態數據表並將其分配給gridview。我需要爲表格的每一行添加一個單選按鈕。但我厭倦了它,無法讓它工作。有人幫助,請....C#ASP.NET中DataTable中的動態單選按鈕

if (dt == null) 
{ 
    dt = new DataTable("Shedules"); 
    DataColumn c0 = new DataColumn("Radio", typeof(RadioButton)); 
    DataColumn c1 = new DataColumn("SID", typeof(System.Int32)); 
    DataColumn c2 = new DataColumn("FID", typeof(System.Int32)); 
    DataColumn c3 = new DataColumn("FROM", typeof(System.String)); 

    dt.Columns.Add(c0); 
    dt.Columns.Add(c1); 
    dt.Columns.Add(c2); 
    dt.Columns.Add(c3); 

    dt.PrimaryKey = new DataColumn[] { c1 }; 
} 


foreach (AgentPortal.SriLankanWebService.Shedule shedule in air1Response) 
{ 
    DataRow dr = dt.NewRow(); 

    RadioButton rb1 = new RadioButton(); 
    rb1.GroupName = "depart"; 
    rb1.ID = shedule.Sid.ToString(); 
    dr["Radio"] = rb1; 

    dr["SID"] = (int)shedule.Sid; 
    dr["FID"] = (int)shedule.Fid; 
    dr["FROM"] = (String)shedule.FromLocation; 
    dt.Rows.Add(dr); 
} 

GridView1.DataSource = dt; 
GridView1.DataBind(); 
+0

您的變量沒有表現出足夠的含義 - 是什麼air1Response?你想達到什麼目的? – codingbiz

+1

你可以把單選按鈕放在GridView本身--DataTable是爲了存儲數據而不是控件 – codingbiz

+0

air1Response是我從Web服務獲得的項目列表。 –

回答

0

包括單選按鈕組的單選按鈕列表中你的GridView

<asp:GridView ID="GridView1" runat="server"> 
<Columns> 

    <asp:TemplateField> 

     <asp:RadioButtonList runat="server" ID="scheduleList" DataTextField="ScheduleName" 
      DataValueField="ScheduleID" /> 

     </asp:TemplateField> 

    <asp:BoundField DataField="SId" HeaderText="SID" /> 
    <asp:BoundField DataField="FId" HeaderText="FID" /> 
    <asp:BoundField DataField="FROMLocation" HeaderText="FROM" /> 
</Columns> 
</asp:GridView> 

在代碼beind

protected void Page_Load(object sender, EventArgs e) 
{ 
    GridView1.DataSource = air1Response; //bind your airResponse directly to GridView 
    GridView1.DataBind(); 

} 

protected void gvSchoolClasses_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    RadioButtonList scheduleList = (RadioButtonList) e.Row.FindControl("scheduleList"); 
    scheduleList = air1Response; 
    scheduleList.DataBind(); 
} 

瞭解更多關於GridView Events