im using asp.net and c#
im using 2 dropdownlist like dd1,dd2
how to fill 2nd dropdownlist dd2 by dd1 onselectindexchanged
my code is,
<asp:DropDownList ID="ddMedType" runat="server" CssClass="drop" AutoPostBack="true" OnSelectedIndexChanged="ddMedType_SelectedIndexChanged">
<asp:ListItem Value="0">-Select-</asp:ListItem>
<asp:ListItem Value="Tablet">Tablet</asp:ListItem>
<asp:ListItem Value="Tonic">Tonic</asp:ListItem>
<asp:ListItem Value="Capsules">Capsules</asp:ListItem>
<asp:ListItem Value="DispoTab">Disposable Tablet</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddMedName" runat="server" CssClass="drop" >
<asp:ListItem Value="0">-Select-</asp:ListItem>
</asp:DropDownList>
protected void ddMedType_SelectedIndexChanged(object sender, EventArgs e)
{
string MedType = ddMedType.SelectedItem.Text;
string str = "select MedicineName,MedicineId from MedicineMaster where MedicineType = '" + MedType + "'";
cmd = new SqlCommand(str, con);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
ddMedName.SelectedValue= reader["MedicineId"].ToString();
}
}
here the condition returns 2 items, but dropdownlist dd2 returns only 1 ...
You are setting the SelectedValue, this does not mean you're adding or removing items in your dropdownlist
DataTable medicines= new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter("select MedicineName,MedicineId from MedicineMaster where MedicineType = '" + MedType + "'", con);
adapter.Fill(subjects);
ddMedName.DataSource = subjects;
ddMedName.DataTextField = "MedicineName";
ddMedName.DataValueField = "MedicineId";
ddMedName.DataBind();
}
catch (Exception ex)
{
// Handle the error
}
}
// Add the initial item - you can add this even if the options from the
// db were not successfully loaded
ddMedName.Items.Insert(0, new ListItem("-Select-", "0"));
You can also do it with the reader as follows:
ddMedName.Items.Clear();
ddMedName.Items.Add(new ListItem("-Select-", "0"));
while (reader.Read())
{
ddMedName.Items.Add(new ListItem(reader["MedicineName"].ToString(), reader["MedicineId"].ToString());
}
Try add item in the DropdownList..
DropDownList1.Items.Add(new ListItem(reader["MedicineId"].ToString(), reader["MedicineId"].ToString()));
Here is one solution may help you:
protected void ddMedType_SelectedIndexChanged(object sender, EventArgs e)
{
string MedType = ddMedType.SelectedItem.Text;
string str = "select MedicineName,MedicineId from MedicineMaster where MedicineType = '" + MedType + "'";
cmd = new SqlCommand(str, con);
SqlDataReader reader = cmd.ExecuteReader();
ddMedName.DataSource = reader;
ddMedName.DataTextField = "MedicineName";
ddMedName.DataValueField = "MedicineId";
ddMedName.DataBind();
}
Related
am trying to fetch values from database table on dropdownlist value change and display them in textbox. While selecting any value from the dropdownlist the page is refreshing but no values are displaying in the textbox and following are the codes:
Default.aspx
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem Text="<Select Subject>" Value="0" />
</asp:DropDownList>
Default.aspx.cs
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string ddl2value = DropDownList1.SelectedValue.ToString();
// fillDropdown3(ddl3, ddl2value);
SqlConnection objConn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand objCmd2;
SqlDataReader objRdr2;
// String strCmd2;
objConn2.Open();
objCmd2 = new SqlCommand("SELECT code, rank, address FROM agen_mast WHERE name = " +
"'" + ddl2value.ToString() + "'", objConn2);
objRdr2 = objCmd2.ExecuteReader();
while (objRdr2.Read())
{
TextBox9.Text = (string)objRdr2["code"].ToString();
TextBox8.Text = (string)objRdr2["address"].ToString().ToUpper();
TextBox10.Text = (string)objRdr2["rank"].ToString().ToUpper();
}
objRdr2.Close();
objConn2.Close();
// Response.Write(ddl2value.ToString());
}
You could try something like this:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if(DropDownList1.SelectedValue !="-1"){
string ddl2value = DropDownList1.SelectedValue.ToString();
SqlConnection objConn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand objCmd2;
SqlDataReader objRdr2;
objConn2.Open();
objCmd2 = new SqlCommand("SELECT code, rank, address FROM agen_mast WHERE name = " +
"'" + ddl2value + "'", objConn2);
objRdr2 = objCmd2.ExecuteReader();
while (objRdr2.Read())
{
TextBox9.Text = (string)objRdr2["code"].ToString();
TextBox8.Text = (string)objRdr2["address"].ToString().ToUpper();
TextBox10.Text = (string)objRdr2["rank"].ToString().ToUpper();
}
objRdr2.Close();
objConn2.Close();
}
}
And add a dummy ListItem with Value -1 as the first item in the DropDownList1 in the .aspx side. By the way, make sure you are sending the correct parameter to SqlCommand. Right now you are looking for a record with Name = 0. Also, ddl2Value is already of type string so you don't need to call ToString() inside SqlCommand
So here in my application I have 2 dropdowns, 4 labels and a gridview. The Medication Type drop list here with the text PO Meds is supposed to generate the number you see between the 2 drop lists, then based on that number, pull all of the records in the medications table with that number as an ID. The medications should populate in the dropdown marked Medication. The first time I run the application it pulls up the correct information but if I try changing that information, instead of the medication dropdown refilling with the new query information it just adds it to the medication droplist.
here are my 2 droplist and code:
HTML
<td>
<asp:DropDownList ID="ddlMedType" runat="server" DataSourceID="sdsMedType" DataTextField="MedType" DataValueField="MedType" AutoPostBack="True" OnSelectedIndexChanged="ddlMedType_SelectedIndexChanged" AppendDataBoundItems="True">
<asp:ListItem Selected="True">Select Medication Type</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="sdsMedType" runat="server" ConnectionString="<%$ ConnectionStrings:SiteSqlServer2 %>" SelectCommand="SELECT [num], [MedType] FROM [pharm_medication_Type]"></asp:SqlDataSource>
<asp:Label ID="lblMedType" runat="server" Visible="true"/>
</td>
<td>
<asp:DropDownList ID="ddlMedication" runat="server" AppendDataBoundItems="True" AutoPostBack="True" OnSelectedIndexChanged="ddlMedication_SelectedIndexChanged" >
<asp:ListItem Selected="True">Choose A Medication</asp:ListItem>
</asp:DropDownList>
</td>
.CS
protected void ddlMedType_SelectedIndexChanged(object sender, EventArgs e)
{
string strMedType = ddlMedType.SelectedValue;
using (SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer2"].ConnectionString))
{
if (ddlMedType.SelectedValue != "Select Medication Type")
{
SqlCommand cmd1 = new SqlCommand("SELECT [num] from [pharm_medication_Type] where [MedType] = #MedType", conn1);
cmd1.Parameters.AddWithValue("#MedType", strMedType);
conn1.Open();
using (SqlDataReader reader2 = cmd1.ExecuteReader())
{
while (reader2.Read())
{
int strNum = reader2.GetInt32(0);
lblMedType.Text = Convert.ToString(strNum);
}
}
string strMedTypeID = lblMedType.Text;
SqlCommand cmd2 = new SqlCommand("Select [MedType_ID], [MedName] from [pharm_medications] where [MedType_ID] = #MedTypeID", conn1);
cmd2.Parameters.AddWithValue("#MedTypeID", strMedTypeID);
ddlMedication.DataSource = cmd2.ExecuteReader();
lblMedType.Text = string.Empty;
ddlMedication.DataTextField = "MedName";
ddlMedication.DataValueField = "MedName";
ddlMedication.DataBind();
ddlMedType.DataBind();
lblMedType.DataBind();
}
}
}
protected void ddlMedication_SelectedIndexChanged(object sender, EventArgs e)
{
string strMedTypeID = lblMedType.Text;
string strMedName = ddlMedication.SelectedValue;
if (ddlMedication.SelectedValue != "Choose A Medication")
{
using (SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer2"].ConnectionString))
{
SqlCommand cmd1 = new SqlCommand(#"SELECT DISTINCT [num], [MedType_ID], [MedName], [MedMin], [MedMax], [ChargingNumber]
FROM [pharm_medications] WHERE [MedType_ID] = #MedTypeID AND [MedName] = #MedName", conn1);
cmd1.Parameters.AddWithValue("#MedTypeID", strMedTypeID);
cmd1.Parameters.AddWithValue("#MedName", strMedName);
conn1.Open();
using (SqlDataReader reader3 = cmd1.ExecuteReader())
{
while (reader3.Read())
{
int myNum = reader3.GetInt32(0);
int strMyMedTypeID = reader3.GetInt32(1);
string strMyMedName = reader3.GetString(2);
string strMedMin = reader3.GetString(3);
string strMedMax = reader3.GetString(4);
string strChargingNumber = reader3.GetString(5);
lblAutoMin.Text = strMedMin;
lblAutoMax.Text = strMedMax;
lblAutoChargeNum.Text = strChargingNumber;
}
}
}
}
}
I am trying to use a drop down list that I have bound to a cell in a GridView to call an SQL UPDATE statement to change a record in the GridView itself. Here is the code below:
<asp:TemplateField HeaderText="Send To...">
<ItemTemplate>
<asp:DropDownList ID="StatusDD" runat="server" AutoPostBack="false" OnSelectedIndexChanged="StatusDD_SelectedIndexChanged">
<asp:ListItem Value="A">Active</asp:ListItem>
<asp:ListItem Value="C">Complete</asp:ListItem>
<asp:ListItem Value="I">In Process</asp:ListItem>
<asp:ListItem Value="E">Error</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
And here is the code behind, this is where my try-catch block hangs my page at ExecuteNonQuery(). Is this the correct syntax of how to do an update? I disabled the AutoPostBack as you can see above but that didn't do anything for me anyway:
protected void StatusDD_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = sender as DropDownList;
ToroGeneral toro = new ToroGeneral();
string connString = toro.GetOracle1ConnectionString();
using (OracleConnection conn1 = new OracleConnection(connString))
{
foreach (GridViewRow row in MMRGrid.Rows)
{
Control ctrl = row.FindControl("StatusDD") as DropDownList;
if (ctrl != null)
{
DropDownList ddl1 = (DropDownList)ctrl;
string qString = "";
// PreQuery work
DropDownList temp = new DropDownList();
temp = (DropDownList)row.FindControl("StatusDD");
string uKey = row.Cells[12].Text;
string tempStr = temp.SelectedValue.ToString().Trim();
if (ddl1.SelectedValue == "A")
{
qString = "UPDATE MATERIALMOVEREQUEST SET PROCESS_FLAG = 'A' WHERE UNIQUEKEY = '" + uKey + "'";
}
else if (ddl1.SelectedValue == "E")
{
qString = "UPDATE MATERIALMOVEREQUEST SET PROCESS_FLAG = 'E' WHERE UNIQUEKEY = '" + uKey + "'";
}
else if (ddl1.SelectedValue == "I")
{
qString = "UPDATE MATERIALMOVEREQUEST SET PROCESS_FLAG = 'I' WHERE UNIQUEKEY = '" + uKey + "'";
}
else if (ddl1.SelectedValue == "C")
{
qString = "UPDATE MATERIALMOVEREQUEST SET PROCESS_FLAG = 'C' WHERE UNIQUEKEY = '" + uKey + "'";
}
else
{
// Error
}
// Change the value of the record in the database.
conn1.Open();
OracleCommand cmd = conn1.CreateCommand();
OracleTransaction myTrans;
cmd.CommandText = qString;
myTrans = conn1.BeginTransaction(IsolationLevel.ReadCommitted);
cmd.Transaction = myTrans;
if (cmd.Connection.State == ConnectionState.Closed)
{
cmd.Connection.Open();
}
try
{
cmd.ExecuteNonQuery();
myTrans.Commit();
}
catch
{
myTrans.Rollback();
}
} // if
} // foreach
}
Why don't you use:
string updateSql = "UPDATE MATERIALMOVEREQUEST SET PROCESS_FLAG = :parameter1 WHEREUNIQUEKEY = :parameter2";"
OracleCommand cmd = new OracleCommand(updateString, conn1);
cmd.BindByName = true;
cmd.Parameters.Add("parameter1", Convert.ToChar(ddl1.SelectedValue);
cmd.Parameters.Add("parameter2", uKey);
myTrans = conn1.BeginTransaction(IsolationLevel.ReadCommitted);
cmd.Transaction = myTrans;
try
{
cmd.ExecuteNonQuery();
myTrans.Commit();
}
catch
{
myTrans.Rollback();
}
Ok I am using the code below in file called autocomplete.asmx (web service file) my main question is do I need to create a different web service for every field I want my auto complete to work for? IE maybe I would like to have the Company Name pulled out instead of country, but another time maybe name, now I know this just involves changing the select statement but How could I go about doing this so that depending on what field it is, it knows what select statement to use?
Thanks
public class AutoComplete : System.Web.Services.WebService
{
[WebMethod]
public string[] GetCountriesList(string prefixText)
{
DataSet dtst = new DataSet();
SqlConnection sqlCon = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
string strSql = "SELECT CountryName FROM Tbl_ooo WHERE CountryName LIKE '" + prefixText + "%' ";
SqlCommand sqlComd = new SqlCommand(strSql, sqlCon);
sqlCon.Open();
SqlDataAdapter sqlAdpt = new SqlDataAdapter();
sqlAdpt.SelectCommand = sqlComd;
sqlAdpt.Fill(dtst);
string[] cntName = new string[dtst.Tables[0].Rows.Count];
int i = 0;
try
{
foreach (DataRow rdr in dtst.Tables[0].Rows)
{
cntName.SetValue(rdr["CountryName"].ToString(), i);
i++;
}
}
catch { }
finally
{
sqlCon.Close();
}
return cntName;
}
}
Yes, you can use same webservice webmethod to populate country and company.
For that you want to use ContextKey property in ajax AutoCompleteExtender control
Below is the sample Code
Markup :
Search
<asp:TextBox ID="txtSearch" CssClass="textBlackBold" runat="server" Width="350px"></asp:TextBox>
<asp:DropDownList ID="ddlType" runat="server" AutoPostBack="True" onselectedindexchanged="ddlType_SelectedIndexChanged">
<asp:ListItem Value="0">Country</asp:ListItem>
<asp:ListItem Value="1">Companies</asp:ListItem>
</asp:DropDownList>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
CompletionListCssClass="autocomplete_completionListElement"
CompletionListItemCssClass="autocomplete_listItem"
CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
EnableCaching="true" ContextKey="Products" UseContextKey="true"
TargetControlID="txtSearch" MinimumPrefixLength="1"
ServiceMethod="GetInfo" ServicePath="~/WebService.asmx" >
</asp:AutoCompleteExtender>
Code Behind C# Code :
protected void ddlType_SelectedIndexChanged(object sender, EventArgs e)
{
string strContextKey = "";
if(ddlType.SelectedValue.ToString() == "0")
strContextKey = "Country";
else
strContextKey = "Companies";
AutoCompleteExtender1.ContextKey = ddlType.SelectedItem.Text;
}
WebService Code :
[WebMethod]
public string[] GetInfo(string prefixText, string contextKey)
{
DataSet dtst = new DataSet();
SqlConnection sqlCon = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
string strSql = "";
if (contextKey == "Country")
{
strSql = "SELECT CountryName FROM Tbl_ooo WHERE CountryName LIKE '" + prefixText + "%' ";
}
else if(contextKey == "Companies")
{
strSql = //Other SQL Query
}
SqlCommand sqlComd = new SqlCommand(strSql, sqlCon);
sqlCon.Open();
SqlDataAdapter sqlAdpt = new SqlDataAdapter();
sqlAdpt.SelectCommand = sqlComd;
sqlAdpt.Fill(dtst);
string[] cntName = new string[dtst.Tables[0].Rows.Count];
int i = 0;
try
{
foreach (DataRow rdr in dtst.Tables[0].Rows)
{
cntName.SetValue(rdr[0].ToString(),i);
i++;
}
}
catch { }
finally
{
sqlCon.Close();
}
return cntName;
}
i m using following code to populate dropdownlist dynamically...
i want that value should be the subject id and text should be the sub_desc...but code is not working the value does not contain the sub_ids...so whats wrong with the code??
(sub_id is integer field)
public void Populate()
{
string ConnectionString = (string)ConfigurationManager.AppSettings["ConnectionString"];
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand popCmd = new SqlCommand("select sub_id,sub_desc from subject", conn);
try
{
conn.Open();
ddlSub.Items.Clear();
SqlDataReader subs;
subs = popCmd.ExecuteReader();
ddlSub.DataSource = subs;
ddlSub.DataValueField = "sub_id";
ddlSub.DataTextField = "sub_desc";
ddlSub.DataBind();
conn.Close();
}
catch (Exception ex)
{
lblMsg.Visible = true;
lblMsg.Text = ex.ToString();
}
}
thanx...
You can set AppendDataBoundItems="true" to ensure data bound items do not clear manually inserted list items.
<asp:DropDownList ID="DropDownList" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="--Select Subject--" Text="--Select Subject--" Selected="true"></asp:ListItem>
</asp:DropDownList>
You can also accomplish this in the code behind.
...
dropSub.Items.Add(new ListItem("--Select Subject--", "0"));
dropSub.AppendDataBoundItems = true;
SqlDataReader subs;
subs = popCmd.ExecuteReader();
ddlSub.DataSource = subs;
ddlSub.DataValueField = "sub_id";
ddlSub.DataTextField = "sub_desc";
ddlSub.DataBind();
conn.Close();
...
You can add you default after databinding. You will need to insert at an index of 0 though rather than Add.