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
Related
I'm trying to develop a web site that receives data from SQL server, then show info on listbox and textbox, and when user select an option then insert data to a table in the database.
My ASP.NET controls are:
<asp:ListBox ID="ListBox1" ClientIDMode="static" runat="server"></asp:ListBox>
<asp:Button ID="btnInsert" runat="server" Text="Start" OnClick="btnInsert_Click" />
I need the data loaded to a listbox, but not sure how to do directly. To retrieve the info and see if its working I did this:
protected void Page_Load(object sender, EventArgs e){
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader reader = cmd.ExecuteReader();
GridView2.DataSource= reader;
GridView2.DataBind();
con.Close();
var nProject = GridView2.Rows.Count;
for (int b = 0; b < nProject ; b++)
{
ListBox1.Items.Add(GridView2.Rows[b].Cells[0].Text);
}
}
Then I tried to set the selected info to a textbox, but nothing happens (because I managed to insert data from textbox to a SQL Server INSERT) :
protected void ListBox1_OnSelectedIndexChanged(object sender, System.EventArgs e)
{
TextBox2.Text = ListBox1.SelectedValue;
Response.Write("ListBox selectedIndexChanged");
}
The info is send back to the database with a button click:
protected void btnInsert_Click(object sender, EventArgs e)
{
var IP = "111.111.11";
txtStatus.Text = "Start";
txtProject.Text = "PR-02";
var indice = 0;
// This always returns "0"
if (ListBox1.SelectedItem != null)
{
indice = ListBox1.SelectedIndex;
}
txtProject.Text = indice.ToString();
// Sql INSERT works fine, but only with info manually created. I can't get the real info to work
SqlConnection con = new SqlConnection("****");
SqlCommand cmd = new SqlCommand(#"INSERT INTO [dbo].[table3]
([project]
,[user_task]
,[status]
,[ip]
,[location])
VALUES
('" + txtProject.Text + "', '" + txtUser.Text + "', '" + txtStatus.Text + "', '" + txtIP.Text + "', '" + txtLocation.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
The Page_Load is one of the first events to run every time there is a call to the server, this means that it runs before the btnInsert_Click event.
This means that you are repopulating the ListBox1 before checking the SelectedItem, this is why it always returns "0"
You have to consider this and use something like
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack || Page.IsCallback) return;
(...)
}
It is hard to understand what you want to do, but I think the ListBox1_OnSelectedIndexChanged is useless if you correct the Page_Load event.
Side notes:
You should really start by putting using statements where you can (on SqlConnection and SqlCommand)
Watch out for Sql Injections, may be a simple test program, but you should NEVER, EVER do this: #"INSERT INTO (...) VALUES ('" + txtProject.Text + "'"
use parameters instead:
using(SqlConnection con = new SqlConnection("****"))
using(SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[table3] ([project]) values (#project)", con))
{
cmd.Parameters.AddWithValue("#project", txtProject.Text);
}
It seems you are using .Net Framework with aspx pages, you should really consider using newer technologies (.net core).
I'm having an issue with a DropDownList dispaying student names. For some reason it loses items after I click a button, which is used for giving them a grade. I'd like to find a way to preserve these items. The button does not, in any way, filter the students displayed. The resulting DropDownLists should also have autopostback set as true. The student names are not retrieved or altered in the code behind so I'm unsure why the names are disappearing from this DropDownList. Any hints/solutions would be welcome. Update: I have attached code from the front end and also code from the .cs file for the button that sends the mark for the student. After entering a score and going back to the module it was entered for the items disappearing problem arises.
<asp:SqlDataSource
ID="SQLStudentList"
runat="server"
ConnectionString="<%$ ConnectionStrings:UniString %>"
SelectCommand="SELECT DISTINCT students_profile.user_id, (first_name + ' ' + last_name ) AS studentDetails FROM students_profile INNER JOIN classlist ON students_profile.user_id = classlist.user_id INNER JOIN class ON class.class_id = classlist.class_id INNER JOIN student_module_grade ON classlist.classlist_id = student_module_grade.classlist_id INNER JOIN student_module_repeat_grades ON student_module_grade.classlist_id = student_module_repeat_grades.classlist_id WHERE class.pathway_year_id = #idpathway AND student_module_grade.module_on_pathway_id =#modpwayid OR student_module_repeat_grades.module_on_pathway_id=#modpwayid">
<SelectParameters>
<asp:ControlParameter Name="idpathway" ControlID="degreeProgDropDown" Type="String"/>
<asp:ControlParameter ControlID="modDropDown" Name="modpwayid" />
</SelectParameters>
</asp:SqlDataSource>
<asp:DropDownList ID="StudentsList"
OnSelectedIndexChanged="StudentsList_SelectedIndexChanged"
runat="server"
width="420"
AutoPostBack="true"
EnableViewState="true"
DataSourceID="SQLStudentList"
DataTextField="studentDetails"
DataValueField="user_id">
</asp:DropDownList>
protected void Page_Load(object sender, EventArgs e)
{
////If there are no students the message below will be displayed
ListItem selectedItem = StudentsList.SelectedItem;
if (selectedItem != null && !String.IsNullOrEmpty(selectedItem.Text))
{
}
else
{
changedFlag.Visible = true;
changedFlag.Text = "There are currently no grades to change for any students for this module on this pathway";
changedFlag.ForeColor = System.Drawing.Color.Red;
EnterFinalMark.Visible = false;
finalMarkAssignment.Visible = false;
submitAssignmentMark.Visible = false;
repeatSubmitAssignmentMark.Visible = false;
}
if (!IsPostBack)
{
StudentsList.DataSource = SQLStudentList;
StudentsList.DataBind();
String userName = Session["UserLoggedOn"].ToString();
String conString = WebConfigurationManager.ConnectionStrings["UniString"].ConnectionString;
SqlConnection myCon = new SqlConnection(conString);
myCon.Open();
String pathwaySelectionQuery = "SELECT pathway_years.id, pathway_years.pathway_year, pathway FROM pathways INNER JOIN pathway_years ON pathways.id = pathway_years.pathway_id";
SqlCommand pathwaySelectionQuerycmd = new SqlCommand(pathwaySelectionQuery, myCon);
SqlDataReader pwayReader = pathwaySelectionQuerycmd.ExecuteReader();
while (pwayReader.Read())
{
//Put pathway year id in this table instead
degreeProgDropDown.Items.Add(new ListItem(pwayReader["pathway_year"] + ": " + pwayReader["pathway"].ToString(), pwayReader["id"].ToString()));
}
myCon.Close();
}
}
protected void repeatSubmitAssignmentMark_Click(object sender, EventArgs e)
{
String connectionString = WebConfigurationManager.ConnectionStrings["UniString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connectionString);
myConnection.Open();
String repeatModgradeID = "SELECT repeat_module_grade_id from student_module_repeat_grades WHERE module_on_pathway_id = '" + modDropDown.SelectedValue + "'";
SqlCommand repeatModuleGradeIDCommand = new SqlCommand(repeatModgradeID, myConnection);
Int32 repeatModGradeIDResult = Convert.ToInt32(repeatModuleGradeIDCommand.ExecuteScalar().ToString());
String repeatFindUserID = "SELECT classlist_id from classlist WHERE user_id = '" + StudentsList.SelectedValue + "'";
SqlCommand repeatFindUserIDCommand = new SqlCommand(repeatFindUserID, myConnection);
Int32 repeatClasslistval = Convert.ToInt32(repeatFindUserIDCommand.ExecuteScalar().ToString());
String modOnPwayValue = modDropDown.SelectedValue;
String repeatGrade = finalMarkAssignment.Text;
Int32 repeatGradeval = Convert.ToInt32(repeatGrade);
//Grade is a pass if it is equal to or greater than 40- otherwise it is a fail
if (repeatGradeval >= 40)
{
//Pass assigned to the string which will be added to the table
String passOrFail = "Pass";
//Assigned to label
pOrF.Text = passOrFail;
}
else
{
//Fail assigned to the string which will be added to the table
String passOrFail = "Fail";
//Assigned to label
pOrF.Text = passOrFail;
}
if (repeatGradeval >= 0 && repeatGradeval <= 100)
{
changedVAL.Visible = false;
SqlCommand addAssignmentGradeCommand = new SqlCommand("UPDATE student_module_repeat_grades SET classlist_id=#repeatClasslistid,module_on_pathway_id=#modOnPwayValue,grade=#grade,result_code=#PF,changed=1 WHERE module_on_pathway_id = '" + modDropDown.SelectedValue + "'", myConnection);
addAssignmentGradeCommand.Parameters.AddWithValue(#"modOnPwayValue", modOnPwayValue);
addAssignmentGradeCommand.Parameters.AddWithValue(#"repeatClasslistid", repeatClasslistval);
addAssignmentGradeCommand.Parameters.AddWithValue(#"grade", repeatGradeval);
addAssignmentGradeCommand.Parameters.AddWithValue(#"PF", pOrF.Text);
addAssignmentGradeCommand.ExecuteNonQuery();
myConnection.Close();
success.Visible = true;
ClientScript.RegisterStartupScript(this.GetType(), "alert", "HideLabel();", true);
success.ForeColor = System.Drawing.Color.Green;
repeatSubmitAssignmentMark.Visible = false;
}
else
{
changedVAL.Visible = true;
changedVAL.Text = "Please enter a grade between 0 and 100";
changedVAL.ForeColor = System.Drawing.Color.Red;
}
}
My initial thought it that you are likely not currently checking if a PostBack is occurring or not within the Page_Load event of your Page, which is going to cause your data to be rebound each time.
You can generally resolve this by just performing a check within the Page_Load event itself :
protected void Page_Load(object sender, EventArgs e)
{
// If it is an initial load
if(!IsPostBack)
{
// Then perform your one-time data binding here
StudentsList.DataSource = SQLStudentList;
StudentsList.DataBind();
}
// Business as usual
}
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();
}
this is my offer.aspx inherits from masterpage
' />
my .cs file
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
offerlistbind();
}
}
public void offerlistbind()
{
db1.strCommand = " select Offer.OfferID, Offer.OfferName,Offer.Amount,Offer.FromDate,Offer.ToDate,Offer.Description,bm_package.PackageName,bm_country.Country from Offer inner join bm_package on Offer.PackageID=bm_package.PackageID inner join bm_country on Offer.CountryID=bm_country.CountryID";
offerlistnew.DataSource = db1.DataSet();
offerlistnew.DataBind();
}
if i click the button instead of firing item command event item dataBound event is working
protected void offerlistnew_ItemCommand1(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "subscribe")
{
int ofid = Convert.ToInt32(e.CommandArgument);
Response.Redirect("http://ecom.bom.tv/default.aspx?Offer=" + ofid + "");
}
}
Please use Hyperlink in place of button. If you use asp button then first it will do post back then it will redirect to another page. But using hyperlink you can directly redirect to another page. You can also increase the performance using this.
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl='http://ecom.bom.tv/default.aspx?Offer=<%# Eval("OfferID") %>'
Text="Subscribe"></asp:HyperLink>
OR
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl='<%# "http://ecom.bom.tv/default.aspx?Offer=" + Eval("OfferID") %>'
Text="Subscribe"></asp:HyperLink>
Let me know if any concern.
use e.commandname in link button
if (e.CommandName == "sel")
{
//Code conn.Open();
int lblintid = Convert.ToInt32(e.CommandArgument.ToString());
string cmd2 = "UPDATE productsTs set recurrent=recurrent+30,biduser='" + HiddenField2.Value + "' where ID = " + e.CommandArgument + "";
SqlCommand x2 = new SqlCommand(cmd2, conn);
x2.ExecuteNonQuery();
conn.Close();
}else if(e.CommandName == "min")
{
//Code conn.Open();
int lblintid = Convert.ToInt32(e.CommandArgument.ToString());
string cmd2 = "UPDATE productsTs set recurrent=recurrent-30,biduser='" + HiddenField2.Value + "' where ID = " + e.CommandArgument + "";
SqlCommand x2 = new SqlCommand(cmd2, conn);
x2.ExecuteNonQuery();
conn.Close();
}
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["erp"].ConnectionString);
con.Open();
string intero = "Select * from judete";
SqlCommand cmd = new SqlCommand(intero, con);
SqlDataReader rdr;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
CheckBoxList check = new CheckBoxList();
check.Visible = true;
check.Text = rdr[1].ToString() + "<br/>";
Panel1.Controls.Add(check);
}
I have the above code that brings up data from table "Judet" and for each row a checkbox. Now I want when I check a checkbox say USA I want to bring data from another table "Localitati" that will display cities from USA.How can I do that? I'm using c# in an asp.net application.
...
string sqlStatement = "Select * from Localitati";
if (cbUS.IsChecked)
{
sqlStatement += " WHERE country = 'USA' ";
}
else if (cbOtherCountry.IsChecked)
{
sqlStatement += " WHERE country = 'OtherCountry' ";
}
Use the OnCheckedChanged event for checkBox.....
CheckBox on an ASP.NET Content Form like
<asp:CheckBox runat="server" ID="chkTest" AutoPostBack="true" OnCheckedChanged="chkTest_CheckedChanged" />
In code behind, keep the following code:
protected void chkTest_CheckedChanged(object sender, EventArgs e)
{
//do action here
}