ASP.NET DropdownList始终插入第一个项目

时间:2014-12-13 21:51:08

标签: asp.net

我的网站上有下拉列表。当我选择任何项目来插入数据库但它没有插入所选项目时,请始终在下拉列表中插入第一个项目。请帮助我该如何解决这个问题?

这是我的代码:

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();

1 个答案:

答案 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--"));
    }