DropdownList DataSource - c#

Hi everyone I have problem about dropdown list. I am using dropdown list with datasource. How can I get that value which I selected ?
// I need a if statement here because my programme doesn't know which value of dropdown list selected and I don't know how to use this with datasource.
if(//if I select quiz 1 from dropdown list ,quiz 1 should list questions.)
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString);
string chooce = "Select Quiz from tblQuiz where Quiz=1 ";
SqlCommand userExist = new SqlCommand(chooce, con);
con.Open();
int temp = Convert.ToInt32(userExist.ExecuteScalar().ToString());
if (temp == 1)
{
if (rbList.Items[0].Selected == true)
{
string cmdStr = "Select Question from tblQuiz where ID=1";
SqlCommand quest = new SqlCommand(cmdStr, con);
lblque.Text = quest.ExecuteScalar().ToString();
con.Close();
}

You can bind the DropDownList in different ways by using List, Dictionary, Enum, DataSet DataTable.
Main you have to consider three thing while binding the datasource of a dropdown.
DataSource - Name of the dataset or datatable or your datasource
DataValueField - These field will be hidden
DataTextField - These field will be displayed on the dropdwon.
you can use following code to bind a dropdownlist to a datasource as a datatable:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
SqlCommand cmd = new SqlCommand("Select * from tblQuiz", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
DropDownList1.DataTextField = "QUIZ_Name";
DropDownList1.DataValueField = "QUIZ_ID"
DropDownList1.DataSource = dt;
DropDownList1.DataBind();
if you want to process on selection of dropdownlist, then you have to change AutoPostBack="true" you can use SelectedIndexChanged event to write your code.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string strQUIZ_ID=DropDownList1.SelectedValue;
string strQUIZ_Name=DropDownList1.SelectedItem.Text;
// Your code..............
}

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
drpCategory.DataSource = CategoryHelper.Categories;
drpCategory.DataTextField = "Name";
drpCategory.DataValueField = "Id";
drpCategory.DataBind();
}
}

Refer to example at this link. It may be help to you.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.dropdownlist.aspx
void Page_Load(Object sender, EventArgs e)
{
// Load data for the DropDownList control only once, when the
// page is first loaded.
if(!IsPostBack)
{
// Specify the data source and field names for the Text
// and Value properties of the items (ListItem objects)
// in the DropDownList control.
ColorList.DataSource = CreateDataSource();
ColorList.DataTextField = "ColorTextField";
ColorList.DataValueField = "ColorValueField";
// Bind the data to the control.
ColorList.DataBind();
// Set the default selected item, if desired.
ColorList.SelectedIndex = 0;
}
}
void Selection_Change(Object sender, EventArgs e)
{
// Set the background color for days in the Calendar control
// based on the value selected by the user from the
// DropDownList control.
Calendar1.DayStyle.BackColor =
System.Drawing.Color.FromName(ColorList.SelectedItem.Value);
}

It depends on how you set the defaults for the dropdown. Use selected value, but you have to set the selected value. For instance, I populate the datasource with the name and id field for the table/list. I set the selected value to the id field and the display to the name. When I select, I get the id field. I use this to search a relational table and find an entity/record.

Related

Set default selected value of ComboBox in DataGridView

My Form consist of a DataGridView and, inside of that, I have one Column as ComboBox.
The ComboBox is getting filled by the database query.
I wanted to display the default value of ComboBox in the DataGridView. I have loaded values in combo box but could not find a way to set a default value for that.
I have added values to a combo box with the following code on the click of the btnLoadCombo button:
private void btnLoadCombo_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["InventoryManagerConnectionString"].ConnectionString);
//Filling ComboBoxes
con.Open();
SqlCommand cmdGetRootCat = new SqlCommand("SELECT * FROM tblProductCategories", con);
SqlDataReader sdaRootCat = cmdGetRootCat.ExecuteReader();
comboBoxCatTest.Items.Clear();
while (sdaRootCat.Read())
{
this.CatCombo.Items.Add(sdaRootCat["Cat_Name"]);
}
//Filling DataGridView
DataTable dt = new DataTable();
dt.Clear();
SqlCommand cmd = new SqlCommand("SELECT Cat_ID, Cat_Name FROM tblProductCategories", con);
SqlDataReader sda = cmd.ExecuteReader();
dt.Load(sda);
dataGridCatList.DataSource = dt;
con.Close();
}
I expect results as shown in image 2.
You can use
foreach(DataGridViewRow row in dataGridCatList.Rows)
{
if(row.Cells[3].Value != null) //ignore last row which is empty
{
if( row.Cells[3].Value.Equals(1018) )
row.Cells[0].Value = this.CatCombo.Items[0];
}
//...and so on
}
You are going through every row with the foreach() loop and compare the value of Cat_ParentCat with row.Cells[3].Value.Equals(Cat_ParentCatValue). If a match is found, set the default value of the ComboBox with row.Cells[0].Value = this.CatCombo.Items[yourDefaultValue];

Drop Down List not returning correct value

I am having a problem where when I try and retrieve the selected value of an item within a drop down, it only brings me back the selected value of the very first item within it.
This is the code I use to fill the drop down list with data from a table within Sql-Server
protected void Page_Load(object sender, EventArgs e)
{
String Sql = #" select * from SupportTeam";
SqlConnection conn = new SqlConnection(Properties.Resources.cString);
SqlDataAdapter DA = new SqlDataAdapter(Sql, Properties.Resources.cString);
DataSet DS = new DataSet();
DA.Fill(DS, "SupportTeam");
DataTable DT = DS.Tables["SupportTeam"];
DropDownList1.DataValueField = "supportTeamID";
DropDownList1.DataTextField = "supportTeamName";
DropDownList1.DataSource = DT;
DropDownList1.DataBind();
}
Everything works fine when I load the web form, all of the items do display within the drop down list but the problem I am having is that when I change the selected item in the drop down then the DataValueField stays the same
Here is an example. I have 2 rows within my table in Sql
SupportTeamID SupportTeamName
5 - Marketing
8 - e-Learning
When I load my web form, the selected index is set at 0 meaning that the DataValueField is 5. When I select e-Learning from the drop down list, when I debug it still says that DataValueField is 5 when it should be 8.
Here is the code I use to retrieve to selected value within a button click event
supportTeamID = Convert.ToInt32(DropDownList1.SelectedValue);
Every time I run this the supportTeamID is always set to 5
Is there something I am doing wrong or missing? Thanks in advance
you must write code when its not IsPostBack
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
String Sql = #" select * from SupportTeam";
SqlConnection conn = new SqlConnection(Properties.Resources.cString);
SqlDataAdapter DA = new SqlDataAdapter(Sql, Properties.Resources.cString);
DataSet DS = new DataSet();
DA.Fill(DS, "SupportTeam");
DataTable DT = DS.Tables["SupportTeam"];
DropDownList1.DataValueField = "supportTeamID";
DropDownList1.DataTextField = "supportTeamName";
DropDownList1.DataSource = DT;
DropDownList1.DataBind();
}
}

How to redirect to certain pages depending on what option that I select for dropdownlist?

I have this table called FACILITIES. I already code it so that when for etc when meeting is selected for first dropdownlist, second dropdownlist will display the FAC_CODE column data that belongs to the FAC_TYPE column data.
The problem is whatever option that i choose for the FAC_CODE which belongs to any FAC_TYPE, it will always redirect to number1.aspx. I wan to make it so that, if I choose Meeting for the FAC_TYPE and whatever option for the FAC_CODE it will go to number1.aspx. If I choose Tutorial for the FAC_TYPE and whatever option for the FAC_CODE it will go to number2.aspx. If I choose Lecture for the FAC_TYPE and whatever option for the FAC_CODE it will go to number2.aspx.
My first dropdownlist name which is the FAC_TYPE field is called ddlFacilityType and my second dropdownlist name which is the FAC_CODE field is called ddlFacility. Both have autopostback ticked. So how to code in the ddlFacility_SelectedIndexChanged event? bumps up for this thread
public partial class MainMenu : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string constr = ConfigurationManager.ConnectionStrings["projectConnectionString"].ToString(); // connection string
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand com = new SqlCommand("select distinct FAC_TYPE from FACILITIES", 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["projectConnectionString"].ToString(); // connection string
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand com = new SqlCommand("select distinct FAC_CODE from FACILITIES 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)
{
Response.Redirect("number1.aspx");
}
}
You can do something like this in on ddlFacility_SelectedIndexChanged handler.
protected void ddlFacility_SelectedIndexChanged(object sender, EventArgs e)
{
if(ddlFacilityType.SelectedItem.ToString() == "Meeting")
{
Response.Redirect("number1.aspx");
}
else if(ddlFacilityType.SelectedItem.ToString() == "Tutorial" || ddlFacilityType.SelectedItem.ToString()=="Lecture")
{
Response.Redirect("number2.aspx");
}
}
You can also do the same thing by the SelectedIndex property of the dropdownlist, in that case, the code would be something like
if(ddlFacilityType.SelectedIndex == 1) //Meeting is at index 1 of the ddlFacilityType dropdown
{
Response.Redirect("number1.aspx");
}

Load Databind DropDownList inside ListView

I have a ListView control that contains a DropDownList control inside the ItemTemplate tag.
I am trying to load the existing list items to the DropDownList using the codes below inside the ItemCommand event of the ListView control:
DropDownList ddlItem = (DropDownList)e.Item.FindControl("ddlItem");
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT ID, Name FROM Items";
SqlDataReader data = cmd.ExecuteReader();
ddlItem.DataSouce = data;
ddlItem.DataTextField = "Name";
ddlItem.DataValueField = "ID";
ddlItem.DataBind();
con.Close();
After binding the items, I want to choose the selected items based from the database records.
Am I missing something?
You should do that in the ListView's ItemDataBound event instead. You will find your DropDownList there via e.Item.FindControl("ddlItem") get the underlying datasource for that item via e.Item.DataItem. Use the debugger if you're unsure about the types.
protected void ListView1_ItemDataBound(Object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
DropDownList ddlItem = (DropDownList) e.Item.FindControl("ddlItem");
var rowView = e.Item.DataItem as DataRowView;
int id = (int)rowView["ID"]; // whatever
// get data from id ...
//ddlItem.DataSouce = data;
//ddlItem.DataTextField = "Name";
//ddlItem.DataValueField = "ID";
//ddlItem.DataBind();
}
}

In C#- Retrieving data from selected item in combo box and fill into data grid view

I want to retrieve data from combo box and fill it into data grid view. I am using Visual Studio C# Windows Form. My application is using MySql database in retrieving data for column price, user, and date. I tried this code but It doesn't fill anything in data grid view. I have no problem filling my database at first but after I added the combo box to be filled in data grid view it didn't work.
Here's the code:
public void loadDataGridView_Main()
{
dgvMain.Rows.Clear();
List<string>[] detailList = a.mysqlSelect(comboProd.SelectedItem + "Select * From sales");
for (int i = 0; i < detailList.Length; i++)
{
dgvMain.Rows.Add(detailList[i][0], detailList[i][1], detailList[i][2], detailList[i][3]);
}
}
Automatically Load in Form.
private void frmMain_Load(object sender, EventArgs e)
{
a = new MyLibrary("localhost", "root", "", "cashieringdb");
loadDataGridView_Main();
dataLog();
fillCombo();
}
comboProd is the variable name for my comboBox
Here's my fillCombo method I have no problem with this
public void fillCombo()
{
string MyConString = "SERVER=localhost;" +
"DATABASE=cashieringdb;" +
"UID=root;" +
"PASSWORD='';";
MySqlConnection connection = new MySqlConnection(MyConString);
string command = "select productAdd from settings";
MySqlDataAdapter da = new MySqlDataAdapter(command, connection);
DataTable dt = new DataTable();
da.Fill(dt);
comboProd.DataSource = dt;
comboProd.DisplayMember = "productAdd";
connection.Close();
}
This function is only for adding products and to be retrieved in ComboBox, for example if I add Apple product it will save into database and the ComboBox will retrieve the product apple to be added on the list.
EDIT
so here's the flow of my program.
in my data grid view I have 1 ComboBox and 3 columns to be field in my data GridView. in the ComboBox it will fill my selected item in database side it will retrieve the value anything that is in the database. That is the reason I coded it this way.
List<string>[] detailList = a.mysqlSelect(comboProd.SelectedItem + "Select *
BUT I am not sure in this line. I am sceptical. I think the wrong is somewhere here.
private void frmMain_Load(object sender, EventArgs e)
{
a = new MyLibrary("localhost", "root", "", "cashieringdb");
fillCombo(); //fill combo before calling loadDataGridView_Main()
loadDataGridView_Main();
dataLog();
}
Just replaced one statement. Now check it.
Use DataGridViewComboBoxColumn class. Set DataSource and assign ValueMember and DisplayMember columns as required. Add the obj to datagridview
DataGridViewComboBoxColumn dgc = new DataGridViewComboBoxColumn();
dgc.DataSource = ds;
dgc.ValueMember = "columnname1";
dgc.DisplayMember = "columnname2"
dataGridView1.Columns.Add(dgc);

Categories

Resources