0

这是我的页面加载代码

protected void Page_Load(object sender, EventArgs e)
    {
        string str = "SELECT BOOK.book_name,BOOK.price,BOOK.author,BOOK.publisher,BOOK.isbn,BOOK_APPROVAL.status,BOOK_APPROVAL.cat_id FROM BOOK INNER JOIN BOOK_APPROVAL ON BOOK.book_id = BOOK_APPROVAL.book_id";

        SqlDataAdapter da = new SqlDataAdapter(str, obj.connect());

        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();

        ds1.Clear();
        DropDownList1.Items.Clear();

        string str1 = "SELECT cat_id,cat_name from CATEGORY";
        SqlDataAdapter da1 = new SqlDataAdapter(str1, obj.connect());
        da1.Fill(ds1);

        DropDownList1.DataSource = ds1;
        DropDownList1.DataTextField = "cat_name";
        DropDownList1.DataValueField = "cat_id";
        DropDownList1.DataBind();
    }

我在同一页面上有一个下拉列表、带有选择按钮的网格视图和一个批准按钮。当我单击选择按钮时,它的值显示在一系列文本框中,然后我从下拉列表中选择一个项目。使用以下代码将其数据值字段分配给变量:

 SqlCommand ddl = new SqlCommand("select cat_id from CATEGORY where cat_name='" + DropDownList1.SelectedItem + "' ", obj.connect());

catID = Convert.ToInt32(ddl.ExecuteScalar());

最后,当我单击批准按钮时,所有文本框的值都被插入到 ID = dropdownlist.datavaluefield 的表中。

我的问题是,当我每次单击 gridviews 选择按钮时,我的下拉列表值会显示多次。

因此,尝试ds1.Clear()DropDownList1.Items.Clear();在页面加载中,它解决了这个问题,但它将我的 Datavaluefield 重置为“1”。所以我不能使用选定的数据值字段插入表中。

那么我该如何解决呢?

4

1 回答 1

4

您只需将代码包装在Page_Load-check 中!Page.IsPostBack

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
        // code here that should be executed only at the first time 
        // and not on consecutive postbacks
    }
}

这些项目ViewState默认存储在 ASP.NET 中。

于 2013-03-01T16:17:18.643 回答