I have a drop down list of categories that is databound. The selection from this populates a gridview. When I delete a category, it is successfully updating my gridview of products (showing no entries), but not he dropdownlist of categories until I re-run the program.
My page load:
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);
}
}
My code to delete a category:
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!";
}
}
My dropdownlist:
<asp:DropDownList ID="DropListCat" runat="server" BackColor="#66FFFF"
Width="200px" AutoPostBack="True" AppendDataBoundItems="True">
</asp:DropDownList>
My connection and binding code. In 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();
}
}
My stored procedure:
CREATE PROCEDURE SelectAllProd
AS
SELECT * FROM Prod;
GO
This is the result after I have attempted to delete a category.
When I re-run the project, the category will have been deleted.
Edit
Actually, it is deleting the category, but it's retaining the original data binding from page load. So I guess I need to work out how to wipe that.
Write
DropListCat.DataBind();
in BtnDeleteCat_Click
I fixed it by clearing the drop down list items before re-binding the data, as so:
// 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.../
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.