创建未在Gridview中更新其职位的用户列表。我希望列表中有一个下拉列表,其中包含所有可能的标题选择以及下拉列表旁边的按钮。然后一个人可以进入并在下拉按钮中更改标题,并将其更新并从列表中删除。
我所有这一切都是我希望它看起来的方式,但我想弄清楚如何将该行中下拉框的SelectedValue传递给OnClick后面的代码。正如您在下面看到的,我能得到的最接近的是在CommandArgument中传递行号。有关如何将特定行的下拉列表的SelectedValue提供给OnClick的任何建议吗?
编辑:也许我应该使用OnRowCommand而不是OnClick?
目前看起来像这样:
John Doe | DropdownList Button
Jane Doe | DropdownList Button
Joe Doe | DropdownList Button
Jeff Doe | DropdownList Button
ASPX
<asp:GridView runat="server" ID="TitleView" OnRowDataBound="TitleView_RowDataBound" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Fullname" HeaderText="Fullname" />
<asp:TemplateField>
<ItemTemplate>
<div class="input-append"><asp:DropDownList CssClass="span5" ID="TitleList" runat="server">
</asp:DropDownList>
<asp:Button ID="lbnView" runat="server" Text="Update" CssClass="btn btn-primary" OnClick="btn_Clicked"
CommandArgument='<%# ((GridViewRow)Container).RowIndex %>'></asp:Button></div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
背后的代码
public void bindTitleView()
{
using (SqlConnection conn = new SqlConnection(""))
{
SqlCommand cmd = new SqlCommand(@"SELECT U.First + ' ' + U.Last as Fullname, U.UserID, T.Name FROM Employees U LEFT JOIN Titles T ON U.Title = T.ID WHERE U.Active = '1' AND U.Title = '92' ORDER BY Fullname ASC", conn);
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet myDataSet = new DataSet();
adp.Fill(myDataSet);
TitleView.DataSource = myDataSet;
TitleView.DataBind();
}
}
protected void TitleView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = (DropDownList)e.Row.FindControl("TitleList");
using (SqlConnection conn = new SqlConnection(""))
{
SqlCommand cmd = new SqlCommand(@"SELECT ID, Name FROM Titles ORDER BY Name ASC", conn);
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable myDataSet = new DataTable();
adp.Fill(myDataSet);
ddl.DataSource = myDataSet;
ddl.DataTextField = "Name";
ddl.DataValueField = "ID";
ddl.DataBind();
}
}
}
protected void btn_Clicked(object sender, EventArgs e)
{
String rowid = ((Button)sender).CommandArgument;
}
解决方案:我添加后,我批准的答案为我工作了!IsPostBack到Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindTitleView();
}
答案 0 :(得分:1)
在你的btn_click中写下面的代码
protected void btn_Clicked(object sender, EventArgs e)
{
Button Sample = sender as Button;
GridViewRow row = Sample.NamingContainer as GridViewRow;
DropDownList drp = row.FindControl("TitleList") as DropDownList;
//Now use drp.SelectedValue
}
}
如果这不是你想要的,请告诉我。
答案 1 :(得分:1)
你可以这样做:
protected void btn_Clicked(object sender, EventArgs e)
{
int line = ((GridViewRow)((Button)sender).Parent.Parent).RowIndex;
DropDownList drp = ((DropDownList)TitleView.Rows[line].FindControl("TitleList"));
//Continue the method
}