C#/ASP.NET gridview databind dropdownlist index changed - c#

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

Related

combobox /dropdownlist in grid view c#.net

I am a newbie to c#.net winforms application. I have a data grid wch displays some data and out of which one of the column shud be made a dropdownlist or combobox. how do I use that in my code. please help.
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
DataGridViewComboBoxColumn combo = (DataGridViewComboBoxColumn)dataGridView1.Rows[e.RowIndex].Cells[3].OwningColumn;
sql = "select NAME FROM Suppliers";
BindingSource bsource = new BindingSource();
bsource.DataSource = obj.SqlDataTable(sql);
dataGridView1.DataSource = bsource;
combo.HeaderText = "Select Supplier";
}
I want to populate the 3rd column of the data grid with supplier name from the corresponding suppliers table.The data grid view is already populated with data from a join query and one of the field is Supplier(wch I mwant to convert to a dropdown or combo box). let me know if you need any further info for clarifications.
I Modified my code as follows:
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.HeaderText = "Suppliers";
//execute sql data adapter to get supplier values
DataTable dt = obj.SqlDataTable("select NAME from CUSTOMERS");
foreach (DataRow supplier in dt.DataSet.Tables[0].Rows)
{
combo.Items.Add(supplier[0]);
}
dataGridView1.Columns.Add(combo);
now am getting a null reference exception at " dt.DataSet.Tables[0].Rows"
. plz help. I am not sure if am missing something.
Try this code
string strcon = #"Data Source=kp;Initial Catalog=Name;Integrated Security=True;Pooling=False";
SqlConnection con;
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt;
DataGridViewComboBoxColumn dgvCmb;
public Form2()
{
InitializeComponent();
grdcmd();
}
public void grdcmd()
{
con = new SqlConnection(strcon);
con.Open();
string qry = "Select * from Dbname";
da = new SqlDataAdapter(qry, strcon);
dt = new DataTable();
da.Fill(dt);
dgvCmb = new DataGridViewComboBoxColumn();
foreach (DataRow row in dt.Rows)
{
dgvCmb.Items.Add(row["Fname"].ToString());
}
dataGridView1.Columns.Add(dgvCmb);
}

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.

Send data from class to winform

I am developing an application using Winforms and C#. I have a class which will fetch master data of one table. The function in the class executes a stored procedure which returns 2 columns of data.
I have one form, which has a Listbox control, TextBox and ComboBox. I would like to:
Display entire data for column 1 on List box.
Display column 1 selected row value on Textbox and column 2 value in Combo Box for the selected row. Value changes based on selection change in Listbox.
Code to get data using the stored procedure:
public void GetDeity()
{
cmd = new SqlCommand();
cmd.Connection = conDB;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "get_DeityMaster";
cmd.ExecuteNonQuery();
return;
}
ListBox Name: lstDeityList
TextBox Name: txtDeityName
ComboBox Name: cmbDeityCategoryName
Please help on how to pass data. Thanks
you need to return data from your method like below, currently your method return nothing.
you may need to change the method implementation to return DataTable or DataSet
public DataTable GetDeity()
{
using(SqlConnection sqlConn = new SqlConnection(conSTR))
using(SqlCommand cmd = new SqlCommand("get_DeityMaster", sqlConn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
sqlConn.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
Now you can bind the Listbox control using returned datatable above, when selected item change event you can bind other text box and combo boxes.
in your Form you can call the class method by creating object of class like below
Yourclass obj = new Yourclass();
DataTable dt= obj.GetDeity();
ListBox1.DataSource = dt;
ListBox1.DisplayMember = "Column1Name";
ListBox1.ValueMember = "Column2Name";
You need to add SelectedIndexChanged event for the ListBox1
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
TextBox1.Text = ((DataRowView)ListBox1.SelectedItem).Row.ItemArray[0].ToString();
// bind the ComboBox as well
}
Change return type of function from void to DataTable. Create SQLAdapter with your command and fill DataTable.
public DataTable GetDeity()
{
DataTable mTable = new DataTable();
cmd = new SqlCommand();
cmd.Connection = conDB;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "get_DeityMaster";
SqlAapter mAdapter = new SqlAdapter(cmd);
mAdapter.Fill(mTable);
return mTable
}
Why don't you hold the fetched data in a datatable. Then assign columns of that datatable to different controls you like.
e.g.
public void GetData()
{
DataTable odt = new DataTable();
odt = obj.GetDeity();
Combobox.DataSource = odt;
.......... set other controls also...
}
public DataTable GetDeity()
{
SqlCommand cmd = new SqlCommand("get_DeityMaster");
cmd.CommandType = CommandType.StoredProcedure;
return getdatatable(cmd); // YOUR DATA FETCHING LOGIC
}

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.

To Display controls based on the dropdownlist selected item?

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

Categories