To Display controls based on the dropdownlist selected item? - c#

For Dropdownlist items i have written the following code:
protected void dropdowndatasrc()
{
con = new OleDbConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
string command = "select eventname from Events";
cmd = new OleDbCommand(command);
dataadapter = new OleDbDataAdapter(command, con);
DataSet dataset = new DataSet();
con.Open();
DataTable dt = new DataTable("PayEvent");
dataadapter.Fill(dt);
DropDownList4.DataSource = dt;
DropDownList4.DataTextField = dt.Columns[0].ToString();
// DropDownList4.DataValueField = dt.Columns[0].ToString();
DropDownList4.DataBind();
}
I have to display controls based on the value of the dropdownlist (in the access database there is a column named payevent in that it has Yes/No datatype if the selected item in the database have 'yes' means display controls if not no controls must be displayed)
I have tried this code but not worked
protected void DropDownList4_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox11.Text = DropDownList4.SelectedItem.Text;
con = new OleDbConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
string query = "select payevent from Events where eventname=#dropdownlist";
con.Open();
//string query="select payevent from Events";
cmd = new OleDbCommand(query, con);
cmd.Parameters.Add("#dropdownlist", selectedtext);
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string value = reader.GetValue((0)).ToString();
TextBox11.Text = value.ToString();
if (value == "True" || value == "true")
{ pnl.Visible = false; }
else if (value == "False" || value == "false")
{ pnl.Visible = true; }
}
}
the table structure as follows:
**eventname payevent**
Work Shop Yes
emsisoft workshop Yes
ECE No
CSE No
Need help !!!

The usually issue is that you make databind on the dropdownlist again after the post back and the value is lost. So on page load, do not call the dropdowndatasrc on post back as:
if(!IsPostBack)
dropdowndatasrc();
same issue: Dropdown list not selecting value asp.net

Related

C#/ASP.NET gridview databind dropdownlist index changed

I am new to .net world and I could not figure out why the below code does not work. I have a dropdownlist populated with DEPARTMENT_NAME and value as DEPARTMENT_ID. I have a gridview which populates the employees data based on department_id selected from dropdown list. I have written the following code but the gridview is not populating. Can someone please help what I am doing wrong here.
protected void ddDepartments_SelectedIndexChanged(object sender, EventArgs e)
{
string connStr = ConfigurationManager.ConnectionStrings["myCon"].ConnectionString;
OracleConnection oConn = new OracleConnection(connStr);
oConn.Open();
string SqlText = "Select * from employees where department_id = :department_id";
OracleCommand cmd = new OracleCommand(SqlText, oConn);
cmd.CommandType = CommandType.Text;
OracleParameter p_department_id = new OracleParameter();
p_department_id.OracleDbType = OracleDbType.Varchar2;
p_department_id.Value = ddDepartments.SelectedItem.Value;
cmd.Parameters.Add(p_department_id);
OracleDataAdapter adapter = new OracleDataAdapter(cmd);
DataTable dtEmployees = new DataTable();
adapter.Fill(dtEmployees);
gvEmployees.DataSource = dtEmployees;
gvEmployees.DataBind();
dtEmployees.Dispose();
adapter.Dispose();
cmd.Dispose();
oConn.Close();
oConn.Dispose();
}
You need to use a Session variable to persist the gridView datasource on Postback which is sent by the dropdownlist.
So right after:
gvEmployees.DataSource = dtEmployees;
gvEmployees.DataBind();
Add:
Session("gvDS") = gvEmployees.DataSource;
In the page Load() method:
if (Session["gvDS"] != null && IsPostBack)
{
gvEmployees.DataSource = Session["gvDS"];
gvEmployees.DataBind();
}
else
BindGridView(); // you initial gvEmployees binding method
Please see my answer #:
Asp.net Web Forms GridView Dynamic Column Issue

How to populate dropdown list with data from database

I have a stored procedure that pulls data from a database and displays it in a text box; it displays for the textboxes but doesn't display for the dropdown list or textbox that has textmode of date.
I've removed the select value option as it was throwing error SelectedValue which is invalid because it does not exist in the list of items.\r\nParameter name: value"
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "PP_spSearchReturnCrate";
if (!string.IsNullOrEmpty(txtReceiptNo.Text.Trim()))
{
cmd.Parameters.Add("#receiptNo", SqlDbType.VarChar).Value = txtReceiptNo.Text.Trim();
}
cmd.Connection = sqlConn;
sqlConn.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter(cmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
String DATE = Convert.ToDateTime(dt.Rows[0]["returnDte"]).ToString("MM/dd/yyyy");
txtReturnDte.Text = DATE;
txtReceipt.Text = dt.Rows[0]["receiptNo"].ToString(); //Where ColumnName is the Field from the DB that you want to display
//ddlCustomer0.Text= dt.Rows[0]["custName"].ToString();
ddlDriver.Text = dt.Rows[0]["driverName"].ToString();
ddlUnitId.Text = dt.Rows[0]["unitId"].ToString();
txtNumber.Text = dt.Rows[0]["qtyReturned"].ToString();
txtLocation.Text = dt.Rows[0]["custLocation"].ToString();
Panel1.Visible = true;
}
else
{
lblmsg.Text = "No Records Found";
Panel1.Visible = false;
btnEdit.Visible = false;
}
I want to be able to show the data from the database in a drop down list as well as the date in textbox
Create a ListItem first, then add it to the dropdown.
ListItem li = new ListItem(dt.Rows[0]["custName"].ToString());
ddlCustomer0.Items.Add(li);

How would I be able to grab the value from a drop down list control after the control has been bound with a filled data set?

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.

How to keep Dropdown value same after refresh the page

I am using three dropdowns, in first dropdown i bind data from sql. In second dropdown i also bind data from sql and the third dropdown is bind according to second dropdown so in second dropdown there is autopostback property true. I have one search button which fetch the result from database on click.
I want to keep all the Dropdownlist value same after my result show on the page. One thing i did is, at the time of button click i make the session and check it at page load when it is not null bind the dropdown value. Till this point it is working fine i am able to bind prevoius selected values.
This is in my master page and result are display in result page, which is using this masterpage.
aspx :
<asp:DropDownList ID="dd_category" runat="server" AutoPostBack="True"
onselectedindexchanged="dd_category_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="dd_subcategory" runat="server" ></asp:DropDownList>
<asp:Button ID="but_go" runat="server" Text="Go" onclick="but_go_Click"/>
page load :
if (!IsPostBack)
{
FillStates();
FillCategory();
}
if (Session["state"] != null)
{
dd_state.SelectedValue = (string) Session["state"];
}
aspx.cs :
private void FillStates()
{
SqlCommand cmd = new SqlCommand("sps_bindcountrystate", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#flag", 2);
cmd.Parameters.AddWithValue("#CountryID", 1);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
dd_state.DataSource = objDs.Tables[0];
dd_state.DataTextField = "s_name";
dd_state.DataValueField = "s_id";
dd_state.DataBind();
dd_state.Items.Insert(0, "Select State");
}
}
protected void dd_category_SelectedIndexChanged(object sender, EventArgs e)
{
int CategoryID = Convert.ToInt32(dd_category.SelectedValue);
FillSubCategory(CategoryID);
}
private void FillCategory()
{
SqlCommand cmd = new SqlCommand("sps_bindcategory", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#flag", 1);
cmd.Parameters.AddWithValue("#CategoryID", 0);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
dd_category.DataSource = objDs.Tables[0];
dd_category.DataTextField = "category_name";
dd_category.DataValueField = "category_id";
dd_category.DataBind();
dd_category.Items.Insert(0, "Select Category");
dd_subcategory.Items.Insert(0, "Select Sub-Category");
}
}
private void FillSubCategory(int CategoryID)
{
SqlCommand cmd = new SqlCommand("sps_bindcategory", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#flag", 2);
cmd.Parameters.AddWithValue("#CategoryID", CategoryID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
dd_subcategory.DataSource = objDs.Tables[0];
dd_subcategory.DataTextField = "subcategory_name";
dd_subcategory.DataValueField = "subcategory_id";
dd_subcategory.DataBind();
dd_subcategory.Items.Insert(0, "Select Sub-Category");
}
}
protected void but_go_Click(object sender, EventArgs e)
{
Session["state"] = dd_state.SelectedValue;
Session["category"] = dd_category.SelectedValue;
Session["subcategory"] = dd_subcategory.SelectedValue;
Response.Redirect("Results.aspx");
}
Now problem is when i again choose some different value in first dropdown and try to choose different value in second dropdown, the second dropdown is having postback so it refreshes page and according to session state it changes my first dropdown value back to prevoius one.
Tell me what to do so that new selected value does'nt change due to page refresh.

how to trigger an event when an item is selected from combobox in c#.net

string Sql_type = "select property_type_id,type_name from lk_tb_property_type";
OleDbCommand cmd_type = new OleDbCommand(Sql_type, con);
OleDbDataReader DR_two = cmd_type.ExecuteReader();
DataTable table_two = new DataTable();
table_two.Load(DR_two);
//begin adding line
DataRow row_two = table_two.NewRow();
row_two["type_name"] = "Select Poperty Name";
row_two["property_type_id"] = 0;
table_two.Rows.InsertAt(row_two, 0);
//end adding a line
combo_type.DataSource = table_two;
combo_type.DisplayMember = "type_name";
combo_type.ValueMember = "property_type_id";
combo_type.Text = "Select Poperty Name";
with this code i am fetching values for a combobox from database.now suppose my combobx is having 2 items named A and B..I have one more combobox...now what i want is that when user chooses item A from combobox the second combobox should display data related to item A when user chooses item B then data related to item B should be displayed...sohow to achieve this...??
you can fetch the data and bind it to combobox2 on SelectedIndexChanged event of combobox1
private void combobox1_SelectedIndexChanged(object sender, EventArgs e)
{
var val = combobox1.SelectedValue;
// fetch data from database
// you need to set SQL parameter value form SelectedValue
combobox2.DataSource = ...; // set this value
combobox2.DisplayMember = .....; // set this value
combobox2.ValueMember = ....; // set this value
}
Please assign an event SelectedIndexChanged and AutoPostBack = true is this is a web Application in C#
In SelectedIndexChanged of combo box write your code. and make AutoPostBack = true of your combobox
You can do like these steps.
First, bind data to comboBox1 (I suppose that your first ComboBox named "comboBox1", and your form named "Form1"), please make sure that your SQL query command is correct for comboBox1
private void Form1_Load(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
string Sql_cust_name = "select customer_name from tb_customer";
OleDbCommand cmd_cust_name = new OleDbCommand(Sql_cust_name, con);
OleDbDataReader DR_cust_name = cmd_cust_name.ExecuteReader();
DataTable table_cust_name = new DataTable();
table_cust_name.Load(DR_cust_name);
DataRow row_cust_name = table_cust_name.NewRow();
row_cust_name["customer_name"] = "Select Customer Name";
table_cust_name.Rows.InsertAt(row_cust_name, 0);
combo_cust_name.DataSource = table_cust_name;
combo_cust_name.DisplayMember = "customer_name";
combo_cust_name.ValueMember = "customer_name";
combo_cust_name.Text = "Select Customer Name";
con.Close();
}
Next, bind data to comboBox2 (I suppose that your second ComboBox named "comboBox2"), you have to get comboBox1.SelectedValue whenever it is changed, this value will be used in the filtering for data in comboBox2, so you have to handle SelectedIndexChanged event for comboBox1, please make sure that you have this code somewhere in your project: this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
To bind data to comboBox2 (I suppose that your second ComboBox named "comboBox2"), you have to get comboBox1.SelectedValue whenever it is changed
private void combo_cust_name_SelectedIndexChanged(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
string customerName = "";
if (combo_cust_name.SelectedValue.GetType() == typeof(DataRowView))
{
DataRowView selectedRow = (DataRowView)combo_cust_name.SelectedValue;
customerName = selectedRow["customer_name"].ToString();
}
else
{
customerName = combo_cust_name.SelectedValue.ToString();
}
string Sql2 = "SELECT customer_number FROM tb_customer WHERE customer_name = '" + customerName + "'";
OleDbCommand cmd_type = new OleDbCommand(Sql2, con);
OleDbDataReader DR_two = cmd_type.ExecuteReader();
DataTable table_two = new DataTable();
table_two.Load(DR_two);
DataRow row_two = table_two.NewRow();
row_two["customer_number"] = "Select Customer Number";
table_two.Rows.InsertAt(row_two, 0);
comboBox2.DataSource = table_two;
comboBox2.DisplayMember = "customer_number";
comboBox2.ValueMember = "customer_number";
comboBox2.Text = "Select Customer Number";
}
Please correct the SQL query command as you want, but don't forget to put a correct filter like my sample code above.

Categories