I have table tblDepartments
with columns DeptID, Department, Description
. I also have dropdownbox drpDepartments
. I want to display the contents of column Department
on the dropdownbox. I tried using this C# code for winforms but it didn't work:
drpDepartments.DataSource = dsDep.Tables["tblDepartment"];
drpDepartments.DisplayMember = "Department";
drpDepartments.ValueMember = "DeptID";
drpDepartments.Text = "Choose Department";
How do I do it using ASP.NET C#? Thanks.
New code (still not working)
sConn = new SqlConnection(sStr);
daEmp = new SqlDataAdapter("SELECT * FROM tblEmployee", sConn);
daDep = new SqlDataAdapter("SELECT * FROM tblDepartment", sConn);
dsEmp = new DataSet();
dsDep = new DataSet();
daEmp.Fill(dsEmp, "tblEmployee");
daDep.Fill(dsDep, "tblDepartment");
dsEmp.Tables["tblEmployee"].PrimaryKey = new DataColumn[] { dsEmp.Tables["tblEmployee"].Columns["EmployeeID"] };
DataTable dt=new DataTable();
daDep.Fill(dt);
drpDepartments.DataTextField = "Department";
drpDepartments.DataValueField = "DeptID";
drpDepartments.DataSource = dt;
drpDepartments.DataBind();
You have to call it like this in asp.net webForms
drpDepartments.DataSource = dsDep.Tables["tblDepartment"];// Set DataSource Table First
drpDepartments.DataTextField = "Department";// Set Column Name of DataTable to set as Text Field
drpDepartments.DataValueField = "DepartmentID";// Set Column Name of DataTable to set as Value Field
drpDepartments.DataBind();
You must be using it from using System.Web.UI.WebControls;
namespace. It seems like you were using winforms namespaces.
DataTextField
is equivalent to DisplayMember
and ValueMember
is equivalent to DataValueField
.
Did you call DataBind()?
drpDepartments.DataSource = dsDep.Tables["tblDepartment"];
drpDepartments.DisplayMember = "Department";
drpDepartments.ValueMember = "DepartmentID";
drpDepartments.Text = "Choose Department";
drpDepartments.DataBind();
drpDepartments.DataSource = ds1;
drpDepartments.DataTextField = "textcol";
drpDepartments.DataValueField = "valuecol";
drpDepartments.DataBind();
after doing this in btn_save method add this..
cmd.Parameters.AddWithValue("@a", drpDepartments.SelectedValue);
hope it helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.