I have state and city dropdownlists(cascaded) as below :
protected void BindStateDropDown()
{
string CS = ConfigurationManager.ConnectionStrings["SportsActiveConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from tblState", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ddlState.DataSource = ds;
ddlState.DataTextField = "StateName";
ddlState.DataValueField = "StateId";
ddlState.DataBind();
}
ddlState.Items.Insert(0, new ListItem("---Select---", "0"));
ddlCity.Items.Insert(0, new ListItem("---Select---", "0"));
}
protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
{
int StatId = Convert.ToInt32(ddlState.SelectedValue);
string CS = ConfigurationManager.ConnectionStrings["SportsActiveConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("spCities", con);
cmd.Parameters.AddWithValue("#StatId", StatId);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ddlCity.DataSource = ds;
ddlCity.DataTextField = "CityName";
ddlCity.DataValueField = "CityId";
ddlCity.DataBind();
}
ddlCity.Items.Insert(0, new ListItem("---Select---", "0"));
}
which i use to insert values to the database as below :
cmd.Parameters.AddWithValue("#State", ddlState.SelectedItem.Text);
cmd.Parameters.AddWithValue("#City", ddlCity.SelectedItem.Text);
This works fine and inserts the state and city in the database table.Now i try to show back the values on the edit page as below :
ddlState.SelectedIndex = ddlState.Items.IndexOf(ddlState.Items.FindByText(rdr["State"].ToString()));
ddlCity.SelectedIndex = ddlCity.Items.IndexOf(ddlCity.Items.FindByText(rdr["City"].ToString()));
The abpve code binds the state but not the City.The city dropdown still shows ---Select---.Once the city is bound, i should be able to select any other city/state and update it again.
Any help will be appreciated
Try this
ddlState.SelectedIndex = ddlState.Items.IndexOf(ddlState.Items.FindByText(rdr["State"].ToString()));
then set city value to hidden value hf_city
hf_city.Value = rdr["City"].ToString();
then close your reader and connection and then again call your function which is created on ddlState_SelectedIndexChanged
int StatId = Convert.ToInt32(ddlState.SelectedValue);
string CS = ConfigurationManager.ConnectionStrings["SportsActiveConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("spCities", con);
cmd.Parameters.AddWithValue("#StatId", StatId);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ddlCity.DataSource = ds;
ddlCity.DataTextField = "CityName";
ddlCity.DataValueField = "CityId";
ddlCity.DataBind();
}
ddlCity.Items.Insert(0, new ListItem("---Select---", "0"));
ddlCity.SelectedIndex = ddlCity.Items.IndexOf(ddlCity.Items.FindByText(hf_city.Value));
Create another method for binding cityDropdownlist:
protected void BindCityDropDown(int StatId)
{
string CS = ConfigurationManager.ConnectionStrings["SportsActiveConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("spCities", con);
cmd.Parameters.AddWithValue("#StatId", StatId);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ddlCity.DataSource = ds;
ddlCity.DataTextField = "CityName";
ddlCity.DataValueField = "CityId";
ddlCity.DataBind();
}
ddlCity.Items.Insert(0, new ListItem("---Select---", "0"));
}
Call this inside dropdownlistselected index change:
protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
{
int StatId = Convert.ToInt32(ddlState.SelectedValue);
BindCityDropdown(StatId);
}
Now in edit section bind citydropdownlist then assign value:
ddlState.SelectedIndex = ddlState.Items.IndexOf(ddlState.Items.FindByText(rdr["State"].ToString()));
int StatId = Convert.ToInt32(ddlState.SelectedValue);
BindCityDropdown(StatId);
ddlCity.SelectedIndex = ddlCity.Items.IndexOf(ddlCity.Items.FindByText(rdr["City"].ToString()));
Related
I am new in using visual studio and ADO.NET. I want to display result from sqlserver database in data gridview.
This is my code but it does not fill data to gridview.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
SqlCommand Cmd = new SqlCommand("sp_Expert_person", con);
con.Open();
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.Add("#takhasos", SqlDbType.VarChar).Value = comboBox1.SelectedText;
SqlDataAdapter da = new SqlDataAdapter(Cmd);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
SqlDataReader reader = Cmd.ExecuteReader();
dt.Load(reader);
dataGridView1.DataSource = dt;
this.dataGridView1.Visible = true;
dataGridView1.DataSource = dt;
}
Why are you binding to grid two times?
If your application is ASP.NET Webforms and you are trying to bind the GridView(ID for the GridView is "dataGridView1"), then make your binding to single time and to bind data for GridView you need to use dataGridView1.DataBind(); after dataGridView1.DataSource = dt;
If your application is WindowsForms application then modify your code like below
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
dataGridView1.DataSource = null;
string connectionString = "Define your connection string here";
using(SqlConnection con = new SqlConnection(connectionString ))
{
SqlCommand cmd = new SqlCommand("sp_Expert_person", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#takhasos", SqlDbType.VarChar).Value = comboBox1.SelectedText;
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
this.dataGridView1.Visible = true;
dataGridView1.DataSource = dt;
}
}
I'm writing a program using C# win forms and SQL Server 2012. In one of my forms I have a combobox a button and a datagrid view. I want the data grid view to be filled every time I change the value in combo box.
This code doesn't work :( (it does not return an error)
private void button1_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(comboBox2.SelectedValue.ToString());
//int idc = 100;
DataSet ptDataset = new DataSet();
string con = ConfigurationManager.ConnectionStrings["secaloFormulaCS"].ToString();
SqlConnection sqlCon = new SqlConnection(con);
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("spDispProductInfo", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#id", id);
sqlCmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(sqlCmd);
da.Fill(ptDataset);
dataGridView2.DataSource = ptDataset;
sqlCon.Close();
}
Try this.
int id = Convert.ToInt32(comboBox2.SelectedValue.ToString());
//int idc = 100;
DataSet ptDataset = new DataSet();
string con = ConfigurationManager.ConnectionStrings["secaloFormulaCS"].ToString();
SqlConnection sqlCon = new SqlConnection(con);
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("spDispProductInfo", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#id", id);
SqlDataAdapter da = new SqlDataAdapter(sqlCmd);
da.Fill(ptDataset);
dataGridView2.DataSource = ptDataset.Tables[0];
sqlCon.Close();
You must Use the Event of your comboBox clik not the button.
Just try to add this button1_click event to the combobox that you have.
Set your Code in SelectedIndexChanged event Of your comboBox
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet ptDataset = new DataSet();
string con = ConfigurationManager.ConnectionStrings["secaloFormulaCS"].ToString();
SqlConnection sqlCon = new SqlConnection(con);
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("spDispProductInfo", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#id", Convert.ToInt32(comboBox2.SelectedValue.ToString()));
sqlCmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(sqlCmd);
da.Fill(ptDataset);
dataGridView2.DataSource = ptDataset;
sqlCon.Close();
}
I have two drop down list in which i am getting data displayed from database.
When College Name in DropDownList2 is selected only related branches must be shown in of that college in DropDownList1 for this i had used a Stored Procedure and it was working fine when i run it in manually by passing Parameteres.
But while executing code i all branches are displayed.do i need have any Post Back ?
Please help me in this scenario.
Below is my code:
string queryString = "select College_Name from Colleges";
string constring = System.Configuration.ConfigurationManager.ConnectionStrings["ConnDBForum"].ConnectionString;
SqlConnection connection = new SqlConnection(constring);
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
DataTable dt = new DataTable();
SqlDataAdapter ad = new SqlDataAdapter(command);
ad.Fill(dt);
if (dt.Rows.Count > 0)
{
DropDownList2.Items.Insert(0, new ListItem(String.Empty, String.Empty));
DropDownList2.DataSource = dt;
DropDownList2.DataTextField = "College_Name";
DropDownList2.DataValueField = "College_Name";
DropDownList2.DataBind();
DropDownList2.Items.Insert(0, new ListItem(String.Empty, String.Empty));
}
SqlCommand Cmd = new SqlCommand("Branch_display", connection);
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.Add(new SqlParameter("#College_Name", DropDownList2.SelectedValue));
DataTable dt1 = new DataTable();
SqlDataAdapter ad1 = new SqlDataAdapter(Cmd);
ad1.Fill(dt1);
if (dt1.Rows.Count > 0)
{
DropDownList1.DataSource = dt1;
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "Name";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem(String.Empty, String.Empty));
}
connection.Close();
}
yes you need to have a post back somethink like this should help
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
string queryString = "select College_Name from Colleges";
string constring=System.Configuration.ConfigurationManager.ConnectionStrings["ConnDBForum"].ConnectionString;
SqlConnection connection = new SqlConnection(constring);
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
DataTable dt = new DataTable();
SqlDataAdapter ad = new SqlDataAdapter(command);
ad.Fill(dt);
if (dt.Rows.Count > 0)
{
DropDownList2.Items.Insert(0, new ListItem(String.Empty, String.Empty));
DropDownList2.DataSource = dt;
DropDownList2.DataTextField = "College_Name";
DropDownList2.DataValueField = "College_Name";
DropDownList2.DataBind();
DropDownList2.Items.Insert(0, new ListItem(String.Empty, String.Empty));
}
connection.Close();
}
}
asp.net render
<asp:dropdownlist ID=" DropDownList2" runat="server" AutoPostBack="True" OnSelectedIndexChanged=" DropDownList2_SelectedIndexChanged">
and action
private void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
string constring=System.Configuration.ConfigurationManager.ConnectionStrings["ConnDBForum"].ConnectionString;
SqlCommand Cmd = new SqlCommand("Branch_display", connection);
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.Add(new SqlParameter("#College_Name", DropDownList2.SelectedValue));
DataTable dt1 = new DataTable();
SqlDataAdapter ad1 = new SqlDataAdapter(Cmd);
ad1.Fill(dt1);
if (dt1.Rows.Count > 0)
{
DropDownList1.DataSource = dt1;
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "Name";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem(String.Empty, String.Empty));
}
connection.Close();
}
Can anyone help please, I am trying to populate the data automatically to my combobox without having to push any button, but by the dropdown control.....
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.AllowDrop == false)
{
SqlConnection conn = new SqlConnection("Data Source=localhost; database=KnowledgeEssentials;Trusted_Connection=yes;connection timeout=30");
SqlDataAdapter adapter = new SqlDataAdapter("SELECT Problem FROM PROBLEMT", conn);
DataTable dt = new DataTable();
DataSet ds = new DataSet();
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = new SqlCommand("SELECT Problem FROM PROBLEMT", conn);
ad.Fill(ds, "Problem");
dataGridView1.DataSource = dt;
//Biding the data with the control
BindingSource bs = new BindingSource();
bs.DataSource = ds;
bs.DataMember = "Problem";
DataGridView dvg = new DataGridView();
this.Controls.Add(dvg);
dvg.DataSource = bs;
for (int i = 0; i < dt.Rows.Count; i++)
{
comboBox1.Items.Add(dt.Rows[i]["Problem"]);
}
}
else
{
}
}
you are missing a } and I hardly believe that SelectedIndexChanged is the best place to populate a combobox. Since obviously you are learning, try to put your code on a button, once it is working fine from the click of the button, you can look for a better place to it, like the form load for example.
also what exactly is the problem? does it give an error?
first create method for fetching data and load in combobox like this
protected void LoadCombo()
{
SqlConnection conn = new SqlConnection("Data Source=localhost;database=KnowledgeEssentials;Trusted_Connection=yes;connection timeout=30");
SqlDataAdapter adapter = new SqlDataAdapter("SELECT Problem FROM PROBLEMT", conn);
DataSet ds = new DataSet();
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = new SqlCommand("SELECT Problem FROM PROBLEMT", conn);
ad.Fill(ds, "Problem");
dataGridView1.DataSource = ds;
dataGridView1.DataBind();
for (int X = 0; X <= ds.Tables[0].Rows.Count - 1; X++)
{
comboBox1.Items.Add(ds.Tables[0].Rows[X]["Problem"].ToString());
}
}
now on page_load call this method
protected void Page_Load()
{
if(ispostback)
{
}
else
{
LoadCombo();
}
}
Answer to the question on how to populate a combobox automatically:
private void Form3_Load(object sender, EventArgs e)
{
using (SqlConnection sc = new SqlConnection())
{
sc.ConnectionString= "database=KnowledgeEssentials;Trusted_Connection=yes;connection timeout=30";
sc.Open();
using (SqlDataAdapter sda = new SqlDataAdapter())
{
DataTable data = new DataTable();
sda.SelectCommand = new SqlCommand("SELECT ID, TypeProblem FROM eL_Section", sc);
sda.Fill(data);
comboBox1.ValueMember = "ID";
comboBox1.DisplayMember = "ID";
comboBox1.DataSource = data;
comboBox2.ValueMember = "TypeProblem";
comboBox2.DisplayMember = "TypeProblem";
comboBox2.DataSource = data;
}
}
using (SqlConnection cn = new SqlConnection())
{
cn.ConnectionString = "database=KnowledgeEssentials;Trusted_Connection=yes;connection timeout=30";
cn.Open();
using (SqlDataAdapter da = new SqlDataAdapter())
{
DataTable dat = new DataTable();
da.SelectCommand = new SqlCommand("SELECT UserName FROM UserT", cn);
da.Fill(dat);
comboBox3.ValueMember = "UserName";
comboBox3.DisplayMember = "UserName";
comboBox3.DataSource = dat;
}
}
// TODO: This line of code loads data into the 'knowledgeEssentialsDataSet.ProblemT' table. You can move, or remove it, as needed.
this.problemTTableAdapter.Fill(this.knowledgeEssentialsDataSet.ProblemT);
}
I've been working on this one since someone teaches me to use gridview to display my search result.
My problem is, I can't even make it work, when I click or hit the search button, nothing happen. I have:
-1 textbox for last name
-2 dropdownlist for the province and city
-and a search(trigger)button
Here's what I've done so far:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_province ORDER BY PROVINCE_NAME ASC", conn);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
ddlProvince.DataSource = dt;
ddlProvince.DataTextField = "PROVINCE_NAME";
ddlProvince.DataValueField = "PROVINCE_CODE";
ddlProvince.DataBind();
}
}
protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_city WHERE PROVINCE_CODE =#pcode", conn);
comm.Parameters.AddWithValue("#pcode", ddlProvince.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
SqlParameter param = new SqlParameter();
param.ParameterName = "#pcode";
param.Value = ddlProvince;
comm.Parameters.Add(param);
}
ddlCity.DataSource = dt;
ddlCity.DataTextField = "CITY_NAME";
ddlCity.DataValueField = "CITY_CODE";
ddlCity.DataBind();
}
private void BindGridView(string field)
{
DataTable dt = new DataTable();
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
try
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_accredited_providers WHERE DOCTOR_CODE =#pcode", conn);
comm.Parameters.AddWithValue("#pcode", ddlProvince.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
SqlParameter param = new SqlParameter();
param.ParameterName = "#pcode";
param.Value = ddlProvince;
comm.Parameters.Add(param);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
else
{
}
// NO RECORDS FOUND
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
BindGridView(txtName.Text.Trim());
}
}
I'm new to this, please assist me. Thanks!
You are not using the field string variable that you are passing to BindGridView and you are mismanaging your SQL parameters (adding the same parameter twice and assigning a DropDown object as a parameter value).
You are adding the same parameter twice.
To fix this, remove this line: comm.Parameters.AddWithValue("#pcode", ddlProvince.SelectedValue);
You are not using the field variable.
To fix this, change this line
param.Value = ddlProvince; // Note: You are assigning a dropdown OBJECT as the value here!
to
param.Value = field;
in your BindGridView function.