我的网站上有下拉列表。当我选择任何项目来插入数据库但它没有插入所选项目时,请始终在下拉列表中插入第一个项目。请帮助我该如何解决这个问题?
这是我的代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetCategory();
}
}
void GetCategory()
{
dlCategory.DataSource = Data.GetDataTable("SELECT * FROM tblCategory");
dlCategory.DataTextField = "CategoryName";
dlCategory.DataValueField = "ID";
dlCategory.DataBind();
dlCategory.Items.Insert(0, new ListItem("--Select--", "0"));
dlCategory.SelectedIndex = dlCategory.Items.IndexOf(dlCategory.Items.FindByText("--Select--"));
}
SqlConnection baglanti = Data.baglan();
SqlCommand tr = new SqlCommand("Insert tblProduct (CategoryID) values(@CategoryID)", baglanti);
tr.Parameters.AddWithValue("@CategoryID", dlCategory.SelectedValue);
tr.ExecuteNonQuery();
答案 0 :(得分:1)
关于代码你的问题有点模糊,如果我误解了,请纠正我,但我认为你想在WebForms中做以下事情:
它不太优雅,但我会这样做:
private SqlConnection _sqlConnection = new SqlConnection();
protected void Page_Load(object sender, EventArgs e)
{
_sqlConnection.ConnectionString = @".." //Assign whatever your ConnectionString is in Data.baglan();
_sqlConnection.Open();
if (!IsPostBack)
{
GetCategory();
}
else
{
//Define your insert something like this, and I would put this into the submit Button_Click event:
if (!String.IsNullOrEmpty(dlCategory.SelectedValue) && dlCategory.SelectedValue != "0")
{
SqlCommand tr = new SqlCommand("Insert tblProduct (CategoryID) values (@CategoryID)", _sqlConnection);
tr.Parameters.AddWithValue("@CategoryID", dlCategory.SelectedValue);
tr.ExecuteNonQuery();
}
else
{
//TODO: Handle wrong selection, eg display an error message..
}
}
}
void GetCategory()
{
dlCategory.DataSource = new SqlCommand("SELECT * FROM tblCategory", _sqlConnection).ExecuteReader();
dlCategory.DataTextField = "CategoryName";
dlCategory.DataValueField = "ID";
dlCategory.DataBind();
dlCategory.Items.Insert(0, new ListItem("--Select--", "0"));
dlCategory.SelectedIndex = dlCategory.Items.IndexOf(dlCategory.Items.FindByText("--Select--"));
}