selected value of dropdown list not changing in template field - c#

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.

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 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.

Cascading DropDownList within an ItemTemplate ASP.NET C#

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");

Update whole contents in gridview via single button click

I need to update my whole gridview details via single button click. Now I have a coding. But I edit the grid view and click the update button, then the first row only update, remainins are not update. pls help. This is my code.
protected void Button8_Click(object sender, EventArgs e)
{
int RowIndex = 0;
{
GridViewRow row = (GridViewRow)GridView1.Rows[RowIndex];
TextBox txtcode = row.FindControl("txtcode") as TextBox;
TextBox txtalt = row.FindControl("txtalt") as TextBox;
TextBox txtdetail = row.FindControl("txtdetails") as TextBox;
SqlConnection myConnection = new SqlConnection("Data Source=SOMATCOSVR2015;
Initial Catalog=SimsVisnu;User ID=sa;Password=aDmin123");
SqlCommand cmd = new SqlCommand("UPDATE Qtattemp SET Code = #Code,
details = #details WHERE Code = #Code", myConnection);
cmd.Parameters.AddWithValue("#Code", txtcode.Text.Trim());
cmd.Parameters.AddWithValue("#details", txtdetail.Text.Trim());
myConnection.Open();
cmd.ExecuteNonQuery();
GridView1.EditIndex = -1;
DataBind();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
Because you are only specifying the index of first row. You need to loop through each row like this:-
int totalRows = GridView1.Rows.Count;
for (int RowIndex = 0; i < totalRows; RowIndex++)
{
GridViewRow row = GridView1.Rows[RowIndex];
TextBox txtcode = row.FindControl("txtcode") as TextBox;
TextBox txtalt = row.FindControl("txtalt") as TextBox;
TextBox txtdetail = row.FindControl("txtdetails") as TextBox;
SqlConnection myConnection = new SqlConnection("Data Source=SOMATCOSVR2015;
Initial Catalog=SimsVisnu;User ID=sa;Password=aDmin123");
SqlCommand cmd = new SqlCommand("UPDATE Qtattemp SET Code = #Code,
details = #details WHERE Code = #Code", myConnection);
cmd.Parameters.AddWithValue("#Code", txtcode.Text.Trim());
cmd.Parameters.AddWithValue("#details", txtdetail.Text.Trim());
myConnection.Open();
cmd.ExecuteNonQuery();
}
Response.Redirect(Request.Url.AbsoluteUri);
Also, I would suggest to create a separate layer to handle DB operations. Consider using the using statement while executing SQL related queries. Also read Can we stop using AddWithValue.
Update:
Side Note:
1) Bind your gridview inside !IsPostBack.
2) Don't bind the gridview again, either inside the loop or outside.
3) I don't find any reason to update the EditIndex using GridView1.EditIndex. Don't update it.

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