Wrox Home  
Search P2P Archive for: Go

  Return to Index  

aspx_beginners thread: DropDownList problem!


Message #1 by m.murray@s... on Thu, 27 Feb 2003 12:26:18
Hi there

I have an error when I'm dynamically setting up an asp.net dropdown list. 
I am setting both the DataValueField AND the DataTextField to equal a 
field called CompanyName from one of my tables. When I view the source 
code of the finished page I see

<option value="Abacus">Abacus</option> 
<option value="EIA">EIA</option> 

which is fine.

When I try and insert the value of this drop down list into a field called 
cmsID in another table, it works, but when I check the database, the 
contents of the field cmsID is "CompanyName" instead of "Abacus" or "EIA" -
what have I done wrong? 

here's the full script...

<SCRIPT language="c#" runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
// Create a new connection object pointing to the database
String strConnection = ConfigurationSettings.AppSettings["CMS"];
  
if (!IsPostBack)
{
//retrieve details from table for dropdown list
String strSQLforListBox = "Select CompanyName From tblCMS";
							
SqlConnection objConnection = new SqlConnection(strConnection);
SqlCommand objCommand = new SqlCommand(strSQLforListBox, objConnection);

//
objConnection.Open();
drpCompanyName.DataSource = objCommand.ExecuteReader();
drpCompanyName.DataTextField = "CompanyName";
drpCompanyName.DataValueField = "CompanyName";
drpCompanyName.DataBind();
objConnection.Close();
}
}

private void btnInsert_Click(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
String strSQL = "INSERT INTO tblCMSLink(cmsId, Website, Comments) VALUES 
(@cmsId,@Website,@Comments)"; 

String strConnection = ConfigurationSettings.AppSettings["CMS"];
SqlConnection objConnection = new SqlConnection(strConnection);

SqlCommand dbComm = new SqlCommand(strSQL, objConnection);

dbComm.Parameters.Add("@cmsId", SqlDbType.VarChar, 100);
dbComm.Parameters.Add("@Website", SqlDbType.VarChar, 100);
dbComm.Parameters.Add("@Comments", SqlDbType.VarChar, 800);

dbComm.Parameters["@cmsID"].Value =drpCompanyName.DataValueField;
dbComm.Parameters["@Website"].Value = txtLink.Text;
dbComm.Parameters["@Comments"].Value = txtComments.Text;

objConnection.Open();
dbComm.ExecuteNonQuery();
objConnection.Close();

}
}

</SCRIPT>

  Return to Index