Dropdown list no repeat data values - c#

How would I stop the repeating of data in my DropDownLists? I couldn't find any good examples of DropDownlists with non repeating values from sql? I tried to make the select statement say Distinct.
Here is my code I am using:
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = (string)Session["name"];
if (!IsPostBack)
{
DropDownList1.AppendDataBoundItems = true;
DropDownList2.AppendDataBoundItems = true;
DropDownList3.AppendDataBoundItems = true;
DropDownList4.AppendDataBoundItems = true;
String strConnString = ConfigurationManager
.ConnectionStrings["connectionString"].ConnectionString;
String strQuery = "select distinct * from dbo.Vehiclemain WHERE ISENABLED = 'YES'";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "Year";
DropDownList1.DataValueField = "ID";
DropDownList1.DataBind();
con.Close();
con.Open();
DropDownList2.DataSource = cmd.ExecuteReader();
DropDownList2.DataTextField = "Make";
DropDownList2.DataValueField = "ID";
DropDownList2.DataBind();
con.Close();
con.Open();
DropDownList3.DataSource = cmd.ExecuteReader();
DropDownList3.DataTextField = "Model";
DropDownList3.DataValueField = "ID";
DropDownList3.DataBind();
con.Close();
con.Open();
DropDownList4.DataSource = cmd.ExecuteReader();
DropDownList4.DataTextField = "Submodel";
DropDownList4.DataValueField = "ID";
DropDownList4.DataBind();
con.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}

It looks like you want to change the drop downs based on the first drop down.
If that's the case, you would want to make the drop down an autopost back as well.
Everytime someone changes the year, a make will be filled based on the year.
Everytime someone changes the make, a model will be filled based on the make .
Everytime someone changes the model , a submodel will be filled based on the model .
The sQL query will be scaffolded as we build the information...
The code below has not been tested.
<asp:DropDownList ID="ddlYearObj" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlObj_SelectedIndexChanged" ></asp:DropDownList>
<asp:DropDownList ID="ddlMakeObj" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlMakeObj_SelectedIndexChanged" Visible="false"></asp:DropDownList>
<asp:DropDownList ID="ddlModelObj" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlModelObj_SelectedIndexChanged" Visible="false"></asp:DropDownList>
<asp:DropDownList ID="ddlSubmodelObj" runat="server" Visible="false"></asp:DropDownList>
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = (string)Session["name"];
if (!IsPostBack)
{
String strConnString = ConfigurationManager
.ConnectionStrings["connectionString"].ConnectionString;
String strQuery = "select distinct Year from dbo.Vehiclemain WHERE ISENABLED = 'YES'";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
ddlYearObj.DataSource = cmd.ExecuteReader();
ddlYearObj.DataTextField = "Year";
ddlYearObj.DataValueField = "Year";
ddlYearObj.DataBind();
con.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
//Visible!? -- All invisible until something is chosen
ddlMakeObj.Visible = false;
ddlModelObj.Visible = false;
ddlSubmodelObj.Visible = false;
}
protected void ddlYearObj_SelectedIndexChanged(object sender, EventArgs e)
{
String strConnString = ConfigurationManager
.ConnectionStrings["connectionString"].ConnectionString;
String strQuery = "select distinct Make from dbo.Vehiclemain WHERE ISENABLED = 'YES' AND YEAR = "+ ddlYearObj.Value;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
ddlMakeObj.DataSource = cmd.ExecuteReader();
ddlMakeObj.DataTextField = "Make";
ddlMakeObj.DataValueField = "Make";
ddlMakeObj.DataBind();
con.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
//Visible!
ddlMakeObj.Visible = true;
ddlModelObj.Visible = false;
ddlSubmodelObj.Visible = false;
}
protected void ddlMakeObj_SelectedIndexChanged(object sender, EventArgs e)
{
String strConnString = ConfigurationManager
.ConnectionStrings["connectionString"].ConnectionString;
String strQuery = "select distinct modelfrom dbo.Vehiclemain WHERE ISENABLED = 'YES' AND YEAR = "+ ddlYearObj.Value;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
ddlModelObj.DataSource = cmd.ExecuteReader();
ddlModelObj.DataTextField = "Model";
ddlModelObj.DataValueField = "Model";
ddlModelObj.DataBind();
con.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
//Visible!
ddlMakeObj.Visible = true;
ddlModelObj.Visible = true;
ddlSubmodelObj.Visible = false;
}
protected void ddlModelObj_SelectedIndexChanged(object sender, EventArgs e)
{
String strConnString = ConfigurationManager
.ConnectionStrings["connectionString"].ConnectionString;
String strQuery = "select distinct Submodelfrom dbo.Vehiclemain WHERE ISENABLED = 'YES' AND YEAR = "+ ddlYearObj.Value + " AND Model = '" + ddlModelObj.Value + "'";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
ddlSubmodelObj.DataSource = cmd.ExecuteReader();
ddlSubmodelObj.DataTextField = "Submodel";
ddlSubmodelObj.DataValueField = "ID";
ddlSubmodelObj.DataBind();
con.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
//Visible!
ddlMakeObj.Visible = true;
ddlModelObj.Visible = false;
ddlSubmodelObj.Visible = true;
}

You are using single query to populate all your dropdowns. Try creating 4 select statments with applying distinct to appropriate column. for ex Make dropdown would have distinct Make in the query.

Related

How to display fixed data on textbox based on cascading dropdown list in C#?

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>

Binding a Date to TextBox in Textmode=Date

I have an update panel with some gridviews being populated on postback as well as some textboxes that are populated through code and an SqlDataReader on _SelectedIndexChanged. Everything is working except for the two date textboxes that are set to TextMode=Date are not populating. I'm sure it's some formatting issue and I've searched and tried a few different things to no avail..... Thanks in advance !
P.s. edited out connection string
public void ddlSO_SelectedIndexChanged(object sender, EventArgs e)
{
String strConnString = "";
String strQuery = "select strServiceOrderNo, strCustomerNo, strCustomerName, strCustomerAddress1, strCustomerAddress2, strCustomerAddress3, strServiceRequestDate, strServiceOrderDate, intStatusCodeID, intRepID from TServiceOrders where" +
" intServiceOrderID = #intServiceOrderID";
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("#intServiceOrderID", ddlSO.SelectedItem.Value);
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
txtCUSTNO.Text = sdr["strCustomerNo"].ToString();
txtSONO.Text = sdr["strServiceOrderNo"].ToString();
txtAddress1.Text = sdr["strCustomerAddress1"].ToString();
txtAddress2.Text = sdr["strCustomerAddress2"].ToString();
txtAddress3.Text = sdr["strCustomerAddress3"].ToString();
txtDateCreated.Text = sdr["strServiceOrderDate"].ToString() ;
txtDateDue.Text = sdr["strServiceRequestDate"].ToString();
txtCustName.Text = sdr["strCustomerName"].ToString();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}

How to bind selected value from database in dropdownlist in asp.net

I am trying to bind a selected item from the database in dropdownlist. I am not getting the users selected data in the dropdownlist instead it loads everything. What i need is to have a default selected value from the database along with other items. Please help me to overcome this problem. Thanking you in advance.
Stored procedure:
CREATE PROCEDURE [dbo].[get_student_details]
#StudentId int = 0
AS
BEGIN
SET NOCOUNT ON;
SELECT
dbo.Student.InstituteId,
dbo.Student.Institute,
dbo.Student.Name,
dbo.Student.Gender,
dbo.Student.Age
FROM
dbo.Student
WHERE
dbo.Student.StudentId = #StudentId
END
My .aspx markup:
<asp:DropDownList ID="ddlInstitute" runat="server"></asp:DropDownList>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:TextBox ID="txtGender" runat="server"></asp:TextBox>
<asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
<asp:Button ID="btnPersonalDetails" runat="server" Text="Search" OnClick="GetStudentDetails"/>
My code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillInstitute();
}
}
public void FillInstitute()
{
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "get_Institute";
cmd.Connection = con;
try
{
con.Open();
ddlInstitute.DataSource = cmd.ExecuteReader();
ddlInstitute.DataTextField = "Institute";
ddlInstitute.DataValueField = "InstituteId";
ddlInstitute.DataBind();
ddlInstitute.Items.Insert(0, new ListItem("--Select--", "0"));
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
public void GetStudentDetails()
{
studentid= 123;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "get_student_details";
cmd.Parameters.Add("#StudentId", SqlDbType.Int).Value = studentid;
cmd.Connection = con;
try
{
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
ddlInstitute.DataValueField= dr["InstituteId"].ToString();
ddlInstitute.DataTextField= dr["Institute"].ToString();
txtName.Text = dr["Name"].ToString();
txtGender.Text = dr["Gender"].ToString();
txtAge.Text = dr["Age"].ToString();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
You have to use SelectedValue property of DropDownList.DataTextField and DataValueField are for specifying which properties from DataSource should be used as Text and Value of drop down list.
Replace these lines:
ddlInstitute.DataValueField= dr["InstituteId"].ToString();
ddlInstitute.DataTextField= dr["Institute"].ToString();
with:
ddlInstitute.SelectedValue= dr["InstituteId"].ToString();
or you can also do:
ddlInstitute.Items.FindByValue(dr["InstituteId"].ToString()).Selected = true;
You can also refer this article
Assuming you know which ID you want to have selected, try something like this:
ddlInstitute.Items.FindByValue(dr["InstituteId"].ToString()).Selected = true;
Try it as a function:
void FN_loadBranch()
{
classname cls = new classname ();
DataTable dt = new DataTable();
dt = cls.FUNCTIONNAMEINCLASS(int id);
dropdown.DataSource = dt;
dropdown.DataValueField = "valuefield";
dropdown.DataTextField = "textfield";
dropdown.DataBind();
ddlBranch.Items.Insert(0, new ListItem("--Select--", "0"));
}
In function:
public DataTable FUNCTIONNAMEINCLASS( int id)
{
try
{
using (SqlConnection cn = new SqlConnection(CLASS.ConnectionString))
{
SqlCommand cmd = new SqlCommand("[storedprocedure]", cn);
cn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ID", SqlDbType.VarChar, 50).Value = id;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
}
Use stored procedure in the function

Trying to get database entries limited to current UserName

I have the database updating with the UserName of the person who uploaded a file and am trying to retrieve only the files the current user uploaded, to display in the gridview.
The page displays the current user name and when that person uploads a file everything is fine. Though when that user hits the search button, all records show up and I get the error:
Error:Invalid column name 'test'
protected void ButtonSearch_Click(object sender, EventArgs e)
{
GridView1.Visible = true;
try
{
string UN = Session["New"].ToString();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlDataReader reader;
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT * FROM UserUpload WHERE UserName = #un";
command.Parameters.Add(new SqlParameter("#un", UN));
command.Connection = conn;
conn.Open();
reader = command.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
conn.Close();
}
catch (Exception ex)
{
LabelMessage.Text = ("Error:" + ex.Message);
}
}
Change this line
string UserSearch = "SELECT * FROM UserUpload WHERE UserName =" + UN;
to
string UserSearch = string.Format("SELECT * FROM UserUpload WHERE UserName ='{0}'",UN);
you want to match to username as string strings are being wrapped in '' in SQL
If you would be matching by number it would work fine as numbers do not have this requirement.
UPDATE to UPDATE:
Change to something like this (untested)
SqlCommand com = new SqlCommand(UserSearch, conn);
{ DataSet ds = com.ExecuteReader();
if (ds.Tables.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
conn.Close();
}
You would benefit from reading this
Use Parameters instead of assinging the Value to the query string
protected void ButtonSearch_Click(object sender, EventArgs e)
{
GridView1.Visible = true;
try
{
string UN = Session["New"].ToString(); ;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string UserSearch = "SELECT * FROM UserUpload WHERE UserName = #un";
SqlCommand com = new SqlCommand(UserSearch, conn);
com.Parameters.Add(new SqlParameter("#un", UN));
com.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
LabelMessage.Text = ("Error:" + ex.Message);
}
}

Populate datagridview by selecting any table from combo box

I have used the following code for displaying names of my SQL db tables in combobox. Now I want when I click on any of these table names from combo box that my DataGridView populates with that table's contents.
I have three tables in my database.
private void Form1_Load(object sender, EventArgs e)
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select table_name from information_schema.tables";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
comboBox1.DataSource = dtRecord;
comboBox1.DisplayMember = "TABLE_NAME";
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void PopulateGridView(string tablename)
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select * from " + tablename;
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.DataSource = dtRecord;
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedValue != null)
{
PopulateGridView(comboBox1.SelectedValue.ToString());
}
}
}
}
Here is my table (datejoin)
rahul sharma 12-1-2011
suresh chand 23-4-2012
prachi shukla 13-2-2011
siddharth malhotra 25-9-2012
saina chopra 12-8-2011
amit mehta 20-3-2012
Subscribe to the combobox's SelectedIndexChanged event and retrieve the selected table name from the combobox. From there, run a query to retrieve the records from the table and bind the result to the datagridview.
Sample:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
con.Open();
string tableName = comboBox1.SelectedText;
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select * from " + tableName;
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dgv.DataSource = dtRecord;
con.Close();
}
You will have a event on combobox SelectedIndexChange and pass name of table to your function
private void ComboBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
RebindGridView(ComboBox1.SelectedValue);
}
Then in your function:
private void RebindGridView(string tablename)
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select * from " + tablename;
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
gridview1.DataSource = dtRecords;
gridview1.DataBind();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Categories

Resources