【发布时间】:2015-07-28 11:06:07
【问题描述】:
我有一个数据绑定类别的下拉列表。从中进行的选择会填充一个网格视图。当我删除一个类别时,它会成功更新我的产品网格视图(不显示条目),但在我重新运行程序之前不会更新类别的下拉列表。
我的页面加载:
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
这是我尝试删除类别后的结果。
当我重新运行项目时,该类别将被删除。
编辑
实际上,它正在删除类别,但它保留了页面加载的原始数据绑定。所以我想我需要弄清楚如何擦除它。
【问题讨论】:
标签: c# asp.net data-binding webforms sql-server-2014