我的asp.net webform上有一个GridView
,后面用C#代码创建了所有列和行。除第一列外,每列中的每个单元格都是DropDownList
,其中DataSource
。
这是我的GridView
:
<asp:GridView ID="gv_Rota" runat="server" AutoGenerateColumns="false" OnRowDataBound="gv_Rota_RowDataBound">
<HeaderStyle BackColor="#6a3d98" ForeColor="White" Height="20" />
<RowStyle HorizontalAlign="Center" Height="20px" Width="100px" />
<AlternatingRowStyle Height="20px" />
</asp:GridView>
列和单元格的c#创建:
private void BindGrid(int Amount)
{
gv_Rota.DataSource = null;
gv_Rota.Columns.Clear();
BoundField bfield = new BoundField();
bfield.HeaderText = "Days";
bfield.DataField = "Days";
gv_Rota.Columns.Add(bfield);
for (int i = 0; i < Amount; i++)
{
int week = i + 1;
string sWeek = "Week " + week.ToString();
TemplateField tfield = new TemplateField();
tfield.HeaderText = sWeek;
gv_Rota.Columns.Add(tfield);
}
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Days", typeof(string)));
dt.Rows.Add("M");
dt.Rows.Add("T");
dt.Rows.Add("W");
dt.Rows.Add("T");
dt.Rows.Add("F");
dt.Rows.Add("S");
dt.Rows.Add("S");
gv_Rota.DataSource = dt;
gv_Rota.DataBind();
}
然后在我RowDataBound
的{{1}}触发器上,我将GridView
控件添加到每个单元格中:
DropDownList
例如在我的页面上显示的内容:
所以我的问题和问题是我现在想要将每个列(第一个除外)保存到数据库,作为&#34;计划周&#34;,并且不知道如何获取所选项的值在所有或任何protected void gv_Rota_RowDataBound(object sender, GridViewRowEventArgs e)
{
for (int i = 1; i <= ColumnCount; i++)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ddlShift = new DropDownList();
ddlShift.ID = "ddlShift";
ddlShift.DataSource = DCListOfShifts;
ddlShift.DataValueField = "SHIFT_ID";
ddlShift.DataTextField = "SHIFT_NAME";
ddlShift.DataBind();
ddlShift.Items.Insert(0, new ListItem("Shift..."));
ddlShift.CssClass = "ddl_rotamanager";
e.Row.Cells[i].Controls.Add(ddlShift);
}
}
}
中,然后将其传递回数据库。 请注意,这不是DropDownLists
。我将从所有selectedindexchanged
中选择项目,然后按一个按钮提交值。请有人给我一些关于如何做到这一点的重点介绍?感谢。
编辑1:响应说明了如何在一行或单个单元格中获取DropDownList的每个值。但是,现在我需要更具体地了解如何获取列中的特定单元格的值而不是行。是否有可能进一步突出这一点?
答案 0 :(得分:2)
使用Gridview.Rows
属性
protected void MyButton_Click(object sender, EventArgs e)
{
foreach(GridViewRow row in gv_Rota.Rows)
{
//find this control in this row
DropDownList dd = row.FindControl("MyDropdown") as DropDownList;
//OR
//find this control in a specific cell
DropDownList day = row.Cells[0].FindControl("MyDropdown") as DropDownList;
DropDownList Week1 = row.Cells[1].FindControl("ddShift") as DropDownList;
//this is just a pseudo-code to determine which dropdown was selected per row.
//You can improve on this
if(dd1.SelectedValue != string.Empty)
thisDay.SelectedWeek = dd1.SelectedValue;
else if(dd2.SelectedValue != string.Empty)
thisDay.SelectedWeek = dd2.SelectedValue;
....
}
}