I am trying to create a cascading dropdownlist in my ASP.NET C# web application. What's supposed to happen is that when the first dropdownlist selected index is changed, it calls the code below and then it populates the second dropdownlist with new values. Problem is that both dropdownlists are coming up as null when I try to populate the second dropdownlist. Seems like the controls aren't being found when I search for them. They are populating on the page load with the correct information inside the ItemTemplateField of the Repeater. How do I have the cascading dropdownlists without Javascript and only C# within the Repeater? Any help is much appreciated. The code below crashes on the line that says ddl2.Items.Clear();
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList) NameRepeater.FindControl("ddlCountry");
DropDownList ddl2 = (DropDownList) NameRepeater.FindControl("ddlState");
ddl2.Items.Clear();
using(SqlConnection conn = new SqlConnection(connString))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT State, StateID FROM States WHERE CountryID = " + ddl.SelectedValue;
cmd.Connection = conn;
conn.Open();
using(SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
ListItem _listStates = new ListItem();
_listStates.Text = sdr["State"].ToString();
_listStates.Value = sdr["StateID"].ToString();
ddl2.Items.Add(_listStates);
}
}
}
}
ddl2.AppendDataBoundItems = true;
ddl2.Items.Insert(0, new ListItem("Select a State", "-1"));
ddl2.SelectedIndex = -1;
}
Don't forget to call DataBind(), it is needed after you populate the dropdown:
ddl2.DataBind();
EDIT:
DropDownList ddl = (DropDownList)NameRepeater.Items[0].FindControl("ddlCountry");
DropDownList ddl2 = (DropDownList)NameRepeater.Items[0].FindControl("ddlState");
Related
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 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 selected this method by objectdatasource in gridview , but the gridview appeared empty
![enter image description here][1]
[1]:gridview photo.jpg
public List<Item> Item_Getall()
{
List<Item> data = new List<Item>();
SqlCommand cmd = new SqlCommand("c_get_all_item",oo.conn);
cmd.CommandType = CommandType.StoredProcedure;
oo.conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
data.Add(new Item());
{
Name_id = (rdr["item_name_id_pk"].ToString());
Name_arabic = (rdr["item_name_arabic"].ToString());
Component_english = (rdr["item_componant"].ToString());
Component_arabic = (rdr["item_componant_arabic"].ToString());
Price = float.Parse(rdr["item_price"].ToString());
Image = (rdr["item_image"].ToString());
Category = (rdr["item_category_name_id_fk"].ToString());
}
}
oo.conn.Close();
return data;
}
UPDATE - Try to make my answer more helpful
If you want to simply bind your data to a gridview, it is very easy to do it on the backend. Lets say you do it in the Page_Load method.
protected void Page_Load(object sender, eventArgs e){
var data = Item_Getall(); //Creates a list of items by calling your method.
gridView.DataSource = data; //assuming the ID of your gridview is "gridView". It might be something different.
gridView.DataBind(); //binds the data to your grid. If you have it set to auto populate, it should essentially list out every public property for each object in the list.
}
I have a dropdown list in a template field that has it's selected value on load set to another field in the gridview. In the rowupdating event the dropdown goes back to the initial selected value and does not retain the new value. I have the method that fills the grid wrapped in a if this.page.IsPostBack on the page_load event. How do I bind the control's new selected value during rowupdating event and ignore it's initial databind??
I have the auto post back property set to true as well.
Here is the rowupdating event ( I am actually inserting into a different table NOT updating this grid)
protected void grd_add_bins__RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)grd_add_bins.Rows[e.RowIndex];
//int id = Int32.Parse(grdBins.DataKeys[e.RowIndex].Value.ToString());
Label room1 = (Label)row.FindControl("grd_add_room");
Label grower1 = (Label)row.FindControl("grd_add_grower_id");
TextBox bins1 = (TextBox)row.FindControl("grd_add_txtbins_to_pack");
DropDownList packas1 = (DropDownList)row.FindControl("grd_add_ddl_pack_as");
TextBox block1 = (TextBox)row.FindControl("grd_add_txt_block");
Label pool1 = (Label)row.FindControl("grd_add_pool");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into t_run_schedule_lots " +
"(record_key,room_id,grower_id,block_id,pool_id,total_bins,pack_as) " +
"values (#rec_id,#room,#grower,#block,#pool,#bins,#pack_as)";
cmd.Parameters.Add("#rec_id", SqlDbType.VarChar).Value = lblRec_key.Text;
cmd.Parameters.Add("#room", SqlDbType.VarChar).Value = room1.Text;
cmd.Parameters.Add("#grower", SqlDbType.VarChar).Value = grower1.Text;
cmd.Parameters.Add("#bins", SqlDbType.Int).Value = Convert.ToInt32(bins1.Text);
cmd.Parameters.Add("#pack_as", SqlDbType.VarChar).Value = packas1.Text;
cmd.Parameters.Add("#block", SqlDbType.VarChar).Value = block1.Text;
cmd.Parameters.Add("#pool", SqlDbType.VarChar).Value = pool1.Text;
cmd.CommandType = CommandType.Text;
cmd.Connection = this.sqlConnection1;
this.sqlConnection1.Open();
// execute insert statement
cmd.ExecuteNonQuery();
this.sqlConnection1.Close();
fill_grid();<-- fills other grid that shows the result of the insert
fill_bins_grid();<-- fills this grid
//Reset the edit index.
grd_add_bins.EditIndex = -1;
//Bind data to the GridView control.
grd_add_bins.DataBind();
}
You need a OnSelectedIndexChanged method.
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