I am trying to populate a dropdown list on pageload with data from the batabase.
While populating I want the dropdown items (<option>) to have the display text which is different from 'value' of the <option>
For example: The dropdown list will show "Title" (column from db) as text on UI, but the 'value' of the <option> should be "ID" (column from db)
How do I achieve this?
Currently my code is like this: (drpReleaseTitle is the ID of the dropdown)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
con1.Open();
SqlCommand releaseTitlecmd = new SqlCommand("select Title from LWMDemo_ReleaseInfo order by ReleaseID", con1);
SqlDataReader releaseTitledr = releaseTitlecmd.ExecuteReader();
while (releaseTitledr.Read())
{
drpReleaseTitle.Items.Add(releaseTitledr.GetValue(0).ToString());
}
con1.Close();
}
}
Try this
drpReleaseTitle.Items.Add(new ListItem("yourtext", "yourvalue"));
It is better to Use Dataset Instead of Data Reader Because it use disconnected architecture so You can Use After Close the connection
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
con1.Open();
SqlCommand releaseTitlecmd = new SqlCommand("select Title from LWMDemo_ReleaseInfo order by ReleaseID", con1);
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = Cmd;
sda.Fill(ds);
if(ds!=null && ds.table.count>0){
if(ds.table[0]!=null && ds.table[0].rows.count>0){
drpReleaseTitle.DataSource=ds.table[0].Title; //Title Column
drpReleaseTitle.DataSourceID=ds.table[0].ID; //ID Column
}
}
con1.Close();
}
}
If you will try add a string to Items in drop down list, it will create a item, that will have text and value as your string. You need to add new ListItem. ListItem contains constructor with text and value as parameters. More about this class you can read here
Related
I have created a Combo box bound to "Clinics" field of a table. I wanted to show "All" on the first line of the Combo box list to show all activities of the clinics by default in a table. When a specific clinic is selected it shows the activities of the selected clinic.
My script looks like this:
[My Code looks like this]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["Myconn"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "select * from [dbo].[EC_HARS_DQ]";
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
sqlconn.Open();
SqlDataAdapter sdr = new SqlDataAdapter(sqlcomm);
DataTable dt = new DataTable();
sdr.Fill(dt);
comboBox1.DisplayMember = "clinic";
comboBox1.DataSource = dt;
sqlconn.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["Myconn"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "select * from [dbo].[EC_HARS_DQ] where clinic='"+comboBox1.Text.ToString()+"'";
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
sqlconn.Open();
SqlDataAdapter sdr = new SqlDataAdapter(sqlcomm);
DataTable dt = new DataTable();
sdr.Fill(dt);
dataGridView1.DataSource = dt;
sqlconn.Close();
}
}
}
First off, refrain from SELECT *, instead select only needed columns.
You can add All using a UNION.
In this example, table name is Categories with the intent to provide the primary key for use after a selection is made and description to display.
SELECT CategoryID, CategoryName FROM dbo.Categories;
Now using a SELECT with 0 in this case to represent an identifier and 'All` to display in the ComboBox then union for all rows in the table.
SELECT 0 AS CategoryID, 'All' AS CategoryName
UNION ALL SELECT CategoryID, CategoryName FROM dbo.Categories;
In code you can read the data into a DataTable, set DisplayMember, in this case to CategoryName and ValueMember to CategoryID.
When a selection is made check SelectedItem, if 0 All is the selection, else an existing primary key would be used for your business logic.
I have combobox in my form which display value from database. I want one default value so I use .text property also and on selected index changed event the label display the corresponding value of the database the code is not working
string cstr = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
private void AddStock_Load(object sender, EventArgs e)
{
bindcombo();
}
private void bindcombo()
{
SqlConnection con = new SqlConnection(cstr);
SqlDataAdapter da = new SqlDataAdapter("SELECT Dname FROM dealer", con);
DataTable dt = new DataTable();
da.Fill(dt);
cmbdealer.DataSource = dt;
cmbdealer.DisplayMember = "Dname";
cmbdealer.Text = "select-Dealer";
con.Close();
}
private void cmbdealer_SelectedIndexChanged(object sender, EventArgs e)
{
dealerdetails();
}
private void dealerdetails()
{
SqlConnection con = new SqlConnection(cstr);
SqlCommand cmd = new SqlCommand("select * from dealer where Dname='" + cmbdealer.Text + "'", con);
con.Open();
SqlDataReader re = cmd.ExecuteReader();
while (re.Read())
{
lbdl.Text = re["Ddlno"].ToString();
lbgst.Text = re["Dgstno"].ToString();
lbadd.Text = re["Daddress"].ToString();
}
}
the above code is working fine but when the form is load all the 3 label shows the database value of the first entry of my dealer table without selecting and value from combobox.
How would I be able to grab the value from a dropdown list control after the control has been bound with a filled data set? Specifically, this control lives in my footer template and when the user tries to add a new row the selected item needs to be retrieved. The problem is after the dropdown list has been populated when you click on "add new" the value always returns null.
ROW COMMAND FUNCTION:
protected void userView_RowCommand(object sender, GridViewCommandEventArgs e)
{
DropDownList addUserRole = (DropDownList)userView.FooterRow.FindControl("editUserRole");
string sqlCommandText = "INSERT INTO Users(USERNAME, PHONE, EMAIL, ROLEIDFK, DEPTIDFK, ACTIVE) VALUES(#username, #phone, #email, #roleidfk, #deptidfk, #active)";
scmd.Parameters.AddWithValue("#roleidfk", addUserRole.SelectedValue.ToString()); // >>>> Returns "AddUserRole was null"
}
DROPDOWN DATABINDING:
private DataTable GetData (string query)
{
var connection = sqlConnect.connect();
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connection.ConnectionString))
{
con.Open();
using(SqlCommand cmd = new SqlCommand(query, con))
{
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
}
}
return dt;
protected void userView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
}
if ( e.Row.RowType == DataControlRowType.Footer)
{
DropDownList ddlUser = (e.Row.FindControl("ddlRoles") as DropDownList );
//query.addDataSetDdl(roles, "DESCRIPTION", "ROLEID", ddlUser);
ddlUser.DataSource = GetData("SELECT * FROM Roles");
ddlUser.DataTextField = "DESCRIPTION";
ddlUser.DataValueField = "ROLEID";
ddlUser.DataBind();
}
The problem is that the FindControl call does not use the correct id of the dropdpwnlist - at least it differs from the one that you use when databinding the dropdownlist:
DropDownList addUserRole = (DropDownList)userView.FooterRow.FindControl("editUserRole")
vs
DropDownList ddlUser = (e.Row.FindControl("ddlRoles") as DropDownList );
FindControl returns null if the control cannot be found, so if you use the correct id, the problem should be solved.
I have two tables called facility and Facilitytype_lookup table with relationship with each other using fac_type column field. In the first drop down list I populate the data using fac_type field on facility table, and if the selected fac_type field value is selected, for example selecting LT, the fac_code belonging to that fac_type will be displayed on the second drop down list which is L.337 and L.338 like in the screenshots. The problem is I want the first dropdownlist names to be in full. For etc MR as Meeting Room, DR as discussion Room, LT for leture Theatre. That';s why I created another table called Facilitytype_lookup with the column field called fac_name. How do I make the first drop down list names to be in full names using column field fac_name??
public partial class MainMenu : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//string constr = ConfigurationManager.ConnectionStrings["serverConnectionString"].ToString(); // connection string
string constr = ConfigurationManager.ConnectionStrings["projectConnectionString"].ToString();
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand com = new SqlCommand("select distinct FAC_TYPE from FACILITY", con);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds); // fill dataset
ddlFacilityType.DataTextField = ds.Tables[0].Columns["FAC_TYPE"].ToString(); // text field name of table dispalyed in dropdown
// to retrive specific textfield name
ddlFacilityType.DataSource = ds.Tables[0]; //assigning datasource to the dropdownlist
ddlFacilityType.DataBind(); //binding dropdownlist
ddlFacilityType.Items.Insert(0, new ListItem(" Select type", "0"));
}
ddlFacility.Items.Insert(0, new ListItem(" Select room", "0"));
}
protected void ddlFacilityType_SelectedIndexChanged(object sender, EventArgs e)
{
//string constr = ConfigurationManager.ConnectionStrings["serverConnectionString"].ToString(); // connection string
string constr = ConfigurationManager.ConnectionStrings["projectConnectionString"].ToString();
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand com = new SqlCommand("select distinct FAC_CODE from FACILITY where FAC_TYPE='" + ddlFacilityType.SelectedValue.ToString() + "'", con);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds); // fill dataset
ddlFacility.DataTextField = ds.Tables[0].Columns["FAC_CODE"].ToString(); // text field name of table dispalyed in dropdown
// to retrive specific textfield name
ddlFacility.DataSource = ds.Tables[0]; //assigning datasource to the dropdownlist
ddlFacility.DataBind(); //binding dropdownlist
ddlFacility.Items.Insert(0, new ListItem(" Select room", "0"));
}
protected void ddlFacility_SelectedIndexChanged(object sender, EventArgs e)
{
Session["roomvalue"] = ddlFacility.SelectedValue;
if (ddlFacilityType.Text == "MR")
{
Response.Redirect("number1.aspx");
}
else if (ddlFacilityType.Text == "DR")
{
Response.Redirect("number1.aspx");
}
else
Response.Redirect("number2.aspx");
}
}
Edited, first dropdownlist will display fac_name values, but after choosing any option in first drop down list, second drop down list doesn't come out anything
public partial class MainMenu : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//string constr = ConfigurationManager.ConnectionStrings["serverConnectionString"].ToString(); // connection string
string constr = ConfigurationManager.ConnectionStrings["projectConnectionString"].ToString();
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand com = new SqlCommand("select distinct facility.FAC_TYPE, facilitytype_lookup.fac_name from FACILITY inner join facilitytype_lookup ON facility.fac_type=facilitytype_lookup.fac_type", con);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds); // fill dataset
ddlFacilityType.DataTextField = ds.Tables[0].Columns["FAC_name"].ToString(); // text field name of table dispalyed in dropdown
// to retrive specific textfield name
ddlFacilityType.DataSource = ds.Tables[0]; //assigning datasource to the dropdownlist
ddlFacilityType.DataBind(); //binding dropdownlist
ddlFacilityType.Items.Insert(0, new ListItem(" Select type", "0"));
}
ddlFacility.Items.Insert(0, new ListItem(" Select room", "0"));
}
protected void ddlFacilityType_SelectedIndexChanged(object sender, EventArgs e)
{
//string constr = ConfigurationManager.ConnectionStrings["serverConnectionString"].ToString(); // connection string
string constr = ConfigurationManager.ConnectionStrings["projectConnectionString"].ToString();
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand com = new SqlCommand("select distinct FAC_CODE from FACILITY where FAC_TYPE='" + ddlFacilityType.SelectedValue.ToString() + "'", con);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds); // fill dataset
ddlFacility.DataTextField = ds.Tables[0].Columns["FAC_CODE"].ToString(); // text field name of table dispalyed in dropdown
// to retrive specific textfield name
ddlFacility.DataSource = ds.Tables[0]; //assigning datasource to the dropdownlist
ddlFacility.DataBind(); //binding dropdownlist
ddlFacility.Items.Insert(0, new ListItem(" Select room", "0"));
}
protected void ddlFacility_SelectedIndexChanged(object sender, EventArgs e)
{
Session["roomvalue"] = ddlFacility.SelectedValue;
if (ddlFacilityType.Text == "MR")
{
Response.Redirect("number1.aspx");
}
else if (ddlFacilityType.Text == "CR")
{
Response.Redirect("number1.aspx");
}
else if (ddlFacilityType.Text == "DR")
{
Response.Redirect("number1.aspx");
}
else
Response.Redirect("number2.aspx");
}
}
using query i have called two columns value from database into one column. the point is now i want to select a value form combobox and put one column value into textbox.
e.g
two column values from database into combobox below
10001 haider <------ when i select this index i want only haider to be viewed into the textbox
10002 fahad
10003 aitazaz
the snippet which i have used for calling the two colums value from database is:
public void account()
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT acc_no, acc_name FROM accounts_record";
MySqlDataAdapter adpt = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adpt.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
cbacc.Items.Add(ds.Tables[0].Rows[i][0] + " " + ds.Tables[0].Rows[i][1]);
}
con.Close();
}
You should be adding values and text to the combobox separately.
Here's an example ComboBox: Adding Text and Value to an Item (no Binding Source).
If you have to display the id in the text you have to do some parsing before putting the selected text into the textbox.
Use ComboBox.SelectedIndexChanged event of the combobox to populate the textbox accordingly. use http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectedindexchanged(v=vs.110).aspx
If you are able to get the 2 value text of the combo box on selection change then you can split it with space (" ") character and take the 2nd string and put it in textbox.
For example
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string[] splitedStr = comboBox1.SelectedText.Split(' ');
textBox1.Text = splitedStr[1];
}
You should use the code as below
private void Form1_Load(object sender, EventArgs e)
{
string conString = "Data Source=\\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True";
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT acc_no +'-' + acc_name as AccNoWithName , acc_no as ActNo FROM accounts_record";
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
DataSet dsn = new DataSet();
adpt.Fill(dsn);
con.Close();
comboBox1.DisplayMember = "AccNoWithName";
comboBox1.ValueMember = "ActNo";
comboBox1.DataSource = dsn.Tables[0];
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Text = comboBox1.SelectedValue.ToString();
}