我在GridView中显示列,其中一列是下拉列表。我希望能够在选择某些内容后立即保存在下拉列表中选择的选项。我用其中一个有文本框的列做了这个,所以我希望用DropDownList做类似的事情。 文本框和下拉列表的代码:
protected void gvPieceDetails_ItemDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.DataRow) {
JobPieceSerialNo SerNo = e.Row.DataItem as JobPieceSerialNo;
if (SerNo != null) {
TextBox txtComment = e.Row.FindControl("txtComment") as TextBox;
txtComment.Text = SerNo.Comment;
txtComment.Attributes.Add("onblur", "UpdateSerialComment(" + SerNo.ID.ToString() + ", this.value);");
DropDownList ddlReasons = (e.Row.FindControl("ddlReasons") as DropDownList);
DataSet dsReasons = DataUtils.GetUnapprovedReasons(Company.Current.CompanyID, "", true, "DBRIEF");
ddlReasons.DataSource = dsReasons;
ddlReasons.DataTextField = "Description";
ddlReasons.DataValueField = "Description";
ddlReasons.DataBind();
ddlReasons.Items.Insert(0, new ListItem("Reason"));
}
}
如何为下拉列表创建更新功能?
protected void DDLReasons_SelectedIndexChanged(object sender, EventArgs e)
{
string sel = ddlReasons.SelectedValue.ToString();
}
public static void UpdateSerialReason(int SerNoID, string Reasons)
{
JobPieceSerialNo SerNo = new JobPieceSerialNo(SerNoID);
SerNo.Reason = sel; //can't find sel value
SerNo.Update();
}
DROPDOWNLIST:
<asp:DropDownList ID="ddlReasons" runat="server" OnSelectedIndexChanged="DDLReasons_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
我创建了一个OnSelectedIndexChanged函数来获取所选值。但是,我如何保存这个价值呢?有没有办法将它传递给UpdateSerialReason函数?
答案 0 :(得分:2)
只需将string sel
声明移到DDLReasons_SelectedIndexChanged
范围之外,即可获取SelectedItem的文本,因为它已包含在您的数据源中。
private string sel;
protected void DDLReasons_SelectedIndexChanged(object sender, EventArgs e)
{
sel = ddlReasons.SelectedItem.Text;
}
public static void UpdateSerialReason(int SerNoID, string Reasons)
{
JobPieceSerialNo SerNo = new JobPieceSerialNo(SerNoID);
SerNo.Reason = sel; // Should now be available
SerNo.Update();
}
以前的方式只能在本地范围内使用,即在声明和使用它的方法中。
答案 1 :(得分:0)
您可以在致电职能时获得所选值:
UpdateSerialReason(/*Some SerNoID*/ 123456, ddlReasons.SelectedValue)
如果您将值保存为Equalsk建议的变量,则在回发完成后您将丢失您的值。如果您需要在另一页上使用您的值,则可以将其保存在会话中。
如果您在一个asp.net页面中工作,您可以按照我上面的建议进行操作。然后你可以跳过DropDownList上的回发并在需要时调用UpdateSerialReason :)
您可能希望添加属性ViewStateMode="Enabled"
和EnableViewState="true"