我使用以下代码将BusinessID绑定为ddlIndustry下拉列表的DataValueField。我想要做的是将选定的ID保存到不同的表(公司)。我用ddlIndustry.SelectedValue做这个。出于某种原因,第一个值始终保存(1),而不是所选值。你有什么想法可能会发生这种情况吗?
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindCountry();
BindIndustry();
}
private void BindCountry()
{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("countries.xml"));
foreach (XmlNode node in doc.SelectNodes("//country"))
{
ddlCountry.Items.Add(new ListItem(node.InnerText, node.Attributes["code"].InnerText));
ddlCountry.SelectedIndex = 94;
}
}
private void BindIndustry()
{
SqlCommand cmd = null;
SqlConnection conn = new SqlConnection(GetConnectionString());
conn.Open();
cmd = new SqlCommand("Select Industry, BusinessID FROM BusinessType", conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
ddlIndustry.DataSource = ds;
ddlIndustry.DataTextField = "Industry";
ddlIndustry.DataValueField = "BusinessID";
ddlIndustry.DataBind();
//ddlIndustry.Items.Insert(0, new System.Web.UI.WebControls.ListItem("-- Please Select Industry --", "0"));
}
private void ExecuteCompanyDetailsInsert()
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO Company (BusinessID, CompanyName, Email, AddressLine1, AddressLine2, Location, Telephone) VALUES "
+ " (@BusinessID, @CompanyName, @Email, @AddressLine1, @AddressLine2, @Location, @Telephone)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[7];
param[0] = new SqlParameter("@BusinessID", SqlDbType.Int);
param[1] = new SqlParameter("@CompanyName", SqlDbType.VarChar, 50);
param[2] = new SqlParameter("@Email", SqlDbType.VarChar, 50);
param[3] = new SqlParameter("@AddressLine1", SqlDbType.VarChar, 50);
param[4] = new SqlParameter("@AddressLine2", SqlDbType.VarChar, 50);
param[5] = new SqlParameter("@Location", SqlDbType.VarChar, 50);
param[6] = new SqlParameter("@Telephone", SqlDbType.VarChar, 50);
param[0].Value = ddlIndustry.SelectedValue;
param[1].Value = company_name.Text;
param[2].Value = company_email.Text;
param[3].Value = address_line_1.Text;
param[4].Value = address_line_2.Text;
param[5].Value = ddlCountry.SelectedItem.Text;
param[6].Value = telephone.Text;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
答案 0 :(得分:5)
首先修改此代码,因为当您的网页回发到服务器时,您的industry dropdown
再次绑定以及selected value lost
if (!Page.IsPostBack)
{
BindCountry();
BindIndustry();
}
然后您可以获得选定的值
ddlIndustry.SelectedValue