I have two dropdownlists named ddFatherEmployeeNumber and ddEmployeeFatherName. Now on load event i am populating ddFatherEmployeeNumber from database. Here is the code
private DataTable LoadComboBoxFatherEmployeeNumber()
{
DataTable dtFatherENo = new DataTable();
using (SqlConnection con = new SqlConnection(Base.GetConnection))
{
using (SqlCommand cmd = new SqlCommand("SELECT Id, EmployeeNo FROM TableFatherMaster", con))
{
cmd.CommandType = CommandType.Text;
con.Open();
SqlDataReader r = cmd.ExecuteReader();
dtFatherENo.Load(r);
}
}
return dtFatherENo;
}
Load Event code is
if (!IsPostBack)
{
ddFatherEmployeeNumber.DataSource = LoadComboBoxFatherEmployeeNumber();
ddFatherEmployeeNumber.DataTextField = "EmployeeNo";
ddFatherEmployeeNumber.DataValueField = "Id";
ddFatherEmployeeNumber.DataBind();
ddFatherEmployeeNumber.Items.Insert(0, new ListItem("Select Father Employee No", "0"));
}
Here is the .aspx code for ddFatherEmployeeNumber
<div class="col-8">
<asp:DropDownList ID="ddFatherEmployeeNumber" runat="server" class="form-control here" AutoPostBack="True" OnSelectedIndexChanged="ddFatherEmployeeNumber_SelectedIndexChanged"></asp:DropDownList>
</div>
Now i want to populate the ddEmployeeFatherName on the bases of ddFatherEmployeeNumber selected value. I mean when a user select employee number from ddFatherEmployeeNumber list then from database, Name of that employee loads and populate the ddEmployeeFatherName. For that purpose i already write a code on ddFatherEmployeeNumber_SelectedIndexChanged Event. Here is the Code.
protected void ddFatherEmployeeNumber_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddEmployeeFatherName.SelectedIndex == 0)
{
}
else
{
using (SqlConnection con = new SqlConnection(Base.GetConnection))
{
using (SqlCommand cmd = new SqlCommand("SELECT Id, Name FROM TableFatherMaster WHERE EmployeeNo=#EmployeeNo ", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#EmployeeNo", ddFatherEmployeeNumber.SelectedValue);
con.Open();
SqlDataReader r = cmd.ExecuteReader();
ddEmployeeFatherName.DataSource = r;
ddEmployeeFatherName.DataBind();
}
}
}
}
Now the problem is, it doesn't loads data into ddEmployeeFatherName.
Here is the picture for clear understanding
Try setting DataTextField and DataValueField properties for ddEmployeeFatherName first, because you're not setting them before using DataBind():
using (SqlConnection con = new SqlConnection(Base.GetConnection))
{
using (SqlCommand cmd = new SqlCommand("SELECT Id, Name FROM TableFatherMaster WHERE EmployeeNo=#EmployeeNo ", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#EmployeeNo", ddFatherEmployeeNumber.SelectedValue);
con.Open();
SqlDataReader r = cmd.ExecuteReader();
ddEmployeeFatherName.DataSource = r;
// set text and value fields
ddEmployeeFatherName.DataTextField = "Name";
ddEmployeeFatherName.DataValueField = "Id";
ddEmployeeFatherName.DataBind();
}
}
If the dropdownlist option values are still empty, try loading SqlDataReader contents into DataTable and use it instead:
using (SqlCommand cmd = new SqlCommand("SELECT Id, Name FROM TableFatherMaster WHERE EmployeeNo=#EmployeeNo ", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#EmployeeNo", ddFatherEmployeeNumber.SelectedValue);
con.Open();
SqlDataReader r = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(r);
ddEmployeeFatherName.DataSource = dt;
ddEmployeeFatherName.DataTextField = "Name";
ddEmployeeFatherName.DataValueField = "Id";
ddEmployeeFatherName.DataBind();
}
Related
I would like to know how can I display fixed data, based on the cascading dropdown list the user chooses? For example, I have 3 dropdown lists, on the last dropdown list if the user chooses "Yes", textbox will display "Position is approved" and if the user chooses "No", textbox will display "Position not approved". This is my code. I don't know what else to, please help.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillPackage();
}
}
private void FillPackage()
{
string strConn = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT TopID, ToPackage FROM TableTop1";
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)
{
ddl1.DataSource = objDs.Tables[0];
ddl1.DataTextField = "ToPackage";
ddl1.DataValueField = "TopID";
ddl1.DataBind();
ddl1.Items.Insert(0, "--Select--");
}
else
{
lblMsg.Text = "No Package found";
}
}
private void FillPurpose(int TopID)
{
string strConn = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT PurposeID, Purpose FROM TablePurpose1 WHERE TopID =#TopID";
cmd.Parameters.AddWithValue("#TopID", TopID);
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)
{
ddl2.DataSource = objDs.Tables[0];
ddl2.DataTextField = "Purpose";
ddl2.DataValueField = "PurposeID";
ddl2.DataBind();
ddl2.Items.Insert(0, "--Select--");
}
else
{
lblMsg.Text = "Please consult with focal person";
}
}
private void FillReason(int PurposeID)
{
string strConn = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT ReasonID, Reason FROM TableReason1 WHERE PurposeID =#PurposeID";
cmd.Parameters.AddWithValue("#PurposeID", PurposeID);
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)
{
ddl3.DataSource = objDs.Tables[0];
ddl3.DataTextField = "Reason";
ddl3.DataValueField = "ReasonID";
ddl3.DataBind();
ddl3.Items.Insert(0, "--Select--");
}
else
{
lblMsg.Text = "Please consult with focal person";
}
}
Since you have a Page_Load method in your snippet I'll consider your are using asp.net web forms. If that is the case you just have to handle the event emitted by the DropDownList component when it is changed.
I'm your c# code you should create a method to handle the event of an item being selected in your DropDownList, something like this:
protected void ItemSelected(object sender, EventArgs e)
{
if (ddl3.SelectedItem.Value == "Yes")
{
// Change text box text
}
}
And then you just have to hook your event handler to the component:
<asp:DropDownList ID="ddl3" runat="server" AutoPostBack="True"
onselectedindexchanged="ItemSelected">
</asp:DropDownList>
I am showing some data on DataGridView in c# windows form App. Here I want to select ID because I have to use it as foreign key but I don't want to show that ID field on grid.
using (SqlConnection con = new SqlConnection(constr))
{
con.Open();
using (SqlCommand command = new SqlCommand("select * from PatientInfo", con))
{
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
DataTable dt = new DataTable();
dt.Load(reader);
datagridpatient.DataSource = dt;
con.Close();
}
}
}
I want to show just name, email, phone. At the same time for further use I need to select ID too.
you can hide the column,
dataGridView.Columns["ColumnName"].Visible = false;
Ex:
using (SqlConnection con = new SqlConnection(constr))
{
if (con.State == ConnectionState.Closed)
{
con.Open();
using (SqlCommand command = new SqlCommand("select * from PatientInfo", con))
{
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
DataTable dt = new DataTable();
dt.Load(reader);
datagridpatient.DataSource = dt;
if (datagridpatient.Columns.Contains("ID")
datagridpatient.Columns["ID"].Visible = false;
con.Close();
}
}
}
}
I am trying to populate a dropdownlist from sql server by using classes as shown below. The code breaks down when it comes to bind the data into the dropdown list. It gives an error on giving the dropdownlist the dataValueField and datatTextField.
HTML... a.aspx
<asp:DropDownList ID="NationalityDropDownList" runat="server" >
</asp:DropDownList>
C#... a.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Classes.Nationality PossibleNationality = new Classes.Nationality();
if (!Page.IsPostBack)
{
DataTable dataTable = PossibleNationality.getNationality();
NationalityDropDownList.DataSource = dataTable;
NationalityDropDownList.DataValueField = "ID";
NationalityDropDownList.DataTextField = "Nationality";
NationalityDropDownList.DataBind();
}
}
Nationality.cs
public class Nationality
{
public DataTable getNationality()
{
SqlConnection conn;
SqlCommand comm;
string connectionString = ConfigurationManager.ConnectionStrings["InformationConnection"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("spGetAllUsers", conn);
comm.CommandType = CommandType.StoredProcedure;
DataTable dataTable;
try
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
dataTable = new DataTable();
da.Fill(dataTable);
}
finally
{
conn.Close();
}
return dataTable;
}
}
SQL procedure....
ALTER PROCEDURE [dbo].[spGetNationalities]
AS
BEGIN
select * from Nationality;
END
This line of code in your getNationalitymethod...
comm = new SqlCommand("spGetAllUsers", conn);
...should be this instead
comm = new SqlCommand("spGetNationalities", conn);
Databinding should work if your Nationality table has columns ID and Nationality
if (!Page.IsPostBack)
{
try
{
using (SqlConnection con = new SqlConnection("Data Source = NIPOON; Initial Catalog = CustomerOrders; Integrated Security = true"))
{
SqlCommand cmd = new SqlCommand("SELECT Name FROM Customer", con);
con.Open();
dropDownList.DataSource = cmd.ExecuteReader();
dropDownList.DataTextField = "Name";
dropDownList.DataValueField = "Name";
dropDownList.DataBind();
}
}
catch (Exception Ex)
{
Console.WriteLine("Error: " + Ex.Message);
}
GetData();
}
I've got a TabContainer control which houses several tabs. Depending on the ActiveIndex property of the TabContainer I would like for a button click to create a Gridview in that tab and bind it to a stored procedure. Currently, the following code works, but there's a lot of code repeated
protected void btnMakeGridView_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
if (TabContainer1.ActiveTabIndex == 0)
{
using (SqlConnection con = new SqlConnection(cs))
{
using (SqlCommand cmd = new SqlCommand("spTest0", con))
{
con.Open();
cmd.CommandType = CommandType.Text;
SqlDataReader rdr = cmd.ExecuteReader();
GridView gv = new GridView();
TabContainer1.Tabs[TabContainer1.ActiveTabIndex].Controls.Add(gv);
gv.DataSource = rdr;
gv.DataBind();
}
}
}
else if (TabContainer1.ActiveTabIndex == 1)
{
using (SqlConnection con = new SqlConnection(cs))
{
using (SqlCommand cmd = new SqlCommand("spTest1", con))
{
con.Open();
cmd.CommandType = CommandType.Text;
SqlDataReader rdr = cmd.ExecuteReader();
GridView gv = new GridView();
TabContainer1.Tabs[TabContainer1.ActiveTabIndex].Controls.Add(gv);
gv.DataSource = rdr;
gv.DataBind();
}
}
}
else if (TabContainer1.ActiveTabIndex == 2)
{
using (SqlConnection con = new SqlConnection(cs))
{
using (SqlCommand cmd = new SqlCommand("spTest2", con))
{
con.Open();
cmd.CommandType = CommandType.Text;
SqlDataReader rdr = cmd.ExecuteReader();
GridView gv = new GridView();
TabContainer1.Tabs[TabContainer1.ActiveTabIndex].Controls.Add(gv);
gv.DataSource = rdr;
gv.DataBind();
}
}
}
else
{
Label1.Text = "You must select a tab to create the GridView in";
}
}
As you can see depending on the ActiveIndex of the TabContainer, a different stored procedure should be created inside each TabPanel. In my example I'm only working with one database so I don't have to worry about passing the connection string as a parameter for a database to connect to. At first blush I had added something like
//pass in the connection string, the stored procedure name and the ActiveTabIndex
public static void DataAccess(string connectionString,string spName, int activeTabIndex)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(spName, con))
{
con.Open();
cmd.CommandType = CommandType.Text;
SqlDataReader rdr = cmd.ExecuteReader();
GridView gv = new GridView();
gv.DataSource = rdr;
gv.DataBind();
}
}
}
UDPATE: Okay, in the meantime I came up with
public partial class _Default : System.Web.UI.Page
{
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnMakeGridView_Click(object sender, EventArgs e)
{
TabContainer1.Tabs[TabContainer1.ActiveTabIndex].Controls.Add(GetData(cs, "spTest", TabContainer1.ActiveTabIndex));
}
public static GridView GetData(string connectionString,string spName, int activeIndex)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(spName, con))
{
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader rdr = cmd.ExecuteReader();
GridView gv = new GridView();
gv.ID = "gv" + activeIndex.ToString();
gv.DataSource = rdr;
gv.DataBind();
return gv;
}
}
}
}
I'm new to c#, as in.
I'm currently working on a search function in c# using 3 DropDownLists and a submit button. When a user select an item on DropDownList and click submit, it will print the table for the respective selection.
There are 3 DropDownLists:
a province,
city,
specialization.
This will search the available doctors that suits the selection. For example I choose province1 on 1st DropDownList, city1 on the 2nd and a psychologist on 3rd, when the submit button is fired, it will print the available doctors that is in province1, city1 and has a specialization of psychologist.
I already have a code, still figuring it out but, when i click the submit button, nothing is happening. Can someone help me?
Here's what I've done so far:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(1000);
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();
ddlProvince.Items.Insert(0, new ListItem("---------------SELECT---------------", "0"));
ddlCity.Items.Insert(0, new ListItem("---------------SELECT---------------", "0"));
ddlSpec.Items.Insert(0, new ListItem("---------------SELECT---------------", "0"));
}
}
protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(1000);
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();
ddlCity.Items.Insert(0, new ListItem("---------------SELECT---------------", "0"));
}
protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(1000);
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_city");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_specialization", conn);
comm.Parameters.AddWithValue("#ccode", ddlCity.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
SqlParameter param = new SqlParameter();
param.ParameterName = "#ccode";
param.Value = ddlCity;
comm.Parameters.Add(param);
}
ddlSpec.DataSource = dt;
ddlSpec.DataTextField = "SPEC_NAME";
ddlSpec.DataValueField = "SPEC_CODE";
ddlSpec.DataBind();
ddlSpec.Items.Insert(0, new ListItem("---------------SELECT---------------", "0"));
}
protected void btnSub_Click(object sender, EventArgs e)
{
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_doctors");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT DOCTOR_NAME FROM emed_doctors where Province = '" + ddlProvince.SelectedItem.ToString() + "'", conn);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
}
}
Make change in this line of code which is in submit button click function
Correct code:
SqlCommand comm = new SqlCommand("SELECT DOCTOR_NAME FROM emed_doctors where province = '" + ddlProvince.SelectedItem.ToString() + "'", conn);
because as you see your code query is incorrent have look to your code which is incorrect
Wrong code:
SqlCommand comm = new SqlCommand("SELECT DOCTOR_NAME FROM emed_doctors where (" + ddlProvince.SelectedItem.ToString() + " ", conn);
Edit:
if you want to display record that you got in DataTable you either need loop through the records or you need to use GridView for that...i think you miss that thing
in above one after where clause you miss the name of the filed you need to made filter on... i have written update code by modifying that condition.
See MSDN for GridView.
You said that after clicking submit, nothing happend. But in btnSub_Click I didn't see anything that displaying the result or changing anything on the page. You should bind dt to some control like a gridview etc.