2015-07-28 39 views
0

我有一個數據綁定類別的下拉列表。從中選擇填充gridview。當我刪除一個類別時,它正在成功更新我的產品網格視圖(不顯示任何條目),但是不會在他重新運行該程序之前刪除類別的下拉列表。數據改變時下拉列表未更新

我的頁面加載:

protected void Page_Load(object sender, EventArgs e) 
    { 
     // Check if loaded for first time. 
     if (!IsPostBack) 
     { 
      // Bind the data displayed in the Dropdownlists. 
      Login.SelectAllCat(DropListCat); 

     } 
    } 

我的代碼刪除一個類別:

protected void BtnDeleteCat_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      // Get int id from selectioin in drop down list. 
      int id = Convert.ToInt32(DropListCat.SelectedValue.ToString()); 
      // Call method to open data base, create command from stored procedure and delete item to database. 
      Login.DeleteCategory(id); 
      // Update the data displayed in the Dropdownlists. 
      Login.SelectAllCat(DropListCat); 


     } 
     catch (NullReferenceException) 
     { 
      LblProdId.Text = "No Category Selected!"; 
     } 
    } 

我的下拉列表:

<asp:DropDownList ID="DropListCat" runat="server" BackColor="#66FFFF" 
      Width="200px" AutoPostBack="True" AppendDataBoundItems="True"> 
</asp:DropDownList> 

我的連接和綁定代碼。在Login class

// Method to select all categories and display them in dropdown lists. 
public static void SelectAllCat(DropDownList list) 
{ 
    // SqlConnection. 
    SqlConnection con = new SqlConnection(conString); 
    // Create new command and parameterise. 
    SqlCommand cmd = new SqlCommand(); 
    cmd.CommandType = CommandType.StoredProcedure; 
    cmd.CommandText = "SelectAllCat"; 
    // 
    // Adapted from 
    // Source link: http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/data-binding-to-dropdownlist-and-listbox-in-Asp-Net/ 
    // 
    cmd.Connection = con; 
    try 
    { 
     // Open connection and bind data to GUI. 
     con.Open(); 

     list.DataSource = cmd.ExecuteReader(); 
     list.DataTextField = "CatName"; 
     list.DataValueField = "CatID"; 
     list.DataBind(); 

    } 
    catch (Exception ex) 
    { 
     throw ex; 
    } 
    finally 
    { 
     con.Close(); 
     con.Dispose(); 
    } 
} 

我的存儲過程:

CREATE PROCEDURE SelectAllProd 
AS 
    SELECT * FROM Prod; 
GO 

這是結果後,我試圖刪除類別。
當我重新運行項目時,該類別將被刪除。
enter image description here

編輯

實際上,它是刪除類別,但它保留了原始數據從頁面加載綁定。所以我想我需要弄清楚如何消除這種情況。

回答

1

DropListCat.DataBind(); 
在BtnDeleteCat_Click

0

我通過重新綁定的數據,所以之前清除下拉列表項固定它:

// Method to select all categories and display them in dropdown lists. 
    public static void SelectAllCat(DropDownList list) 
    { 
     // Clear any previously bound items. 
     list.Items.Clear(); 
     // etc.../ 
相關問題