Disappearing items on DropDownList - c#

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
}

Related

Issue with checking DropDownList's Selected Value exist in Database or Not

I have a web page and there I have fields to hold some data.
One of the fields holds the IDs and names of students enrolled in a particular course. I want to be able to enroll new students to the course using a drop-down list. If the item selected in the drop-down list already exists in the Courses Table, I should display an error message.
I have a code to do these but when I select an already existing value in the drop-down list it doesn't show an error message. It assumes it's a new value and throws an exception because the Database doesn't accept duplicate records.
How can I solve this problem?
I use c# language to design this web page in ASP.NET.
protected void DropDownList1_SelectedIndexChanged(object sender,
EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Ceng.mdf;Integrated Security=True");
string qs = Request.QueryString["id"];
// Variable qs Keeps CourseID retrieved from query string
string sv = DropDownList1.SelectedItem.Value;
// Variable sv keeps selected value from DropDownList
SqlCommand cmd = new SqlCommand("Select * from Enrolment as e, Students as s where e.StudentID = s.StudentID and " +
"CourseID = " + qs + " and StudentName = '" + sv +"'", con);
// There are Students, Courses, and Enrolment tables in database
// Students table columns are StudentID, StudentName, BirthDate
// Course table columns are CourseID, CourseCode, CourseName, Instructor
// Enrolment table columns are CourseID and StudentID
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if(reader.HasRows)
{
Label1.Visible = true;
Label1.Text = "The selected student is already registered to the course!";
Label1.ForeColor = Color.Red;
}
else
{
Label1.Visible = true;
Label1.Text = "The selected student is succesfully registered!";
Label1.ForeColor = Color.Green;
SqlDataSource4.Insert();
GridView1.DataBind();
}
reader.Close();
con.Close();
}
When i select a name from DropDownList which is not exist in Database, i get proper result.
For example, Think about "Jeff Bezos" is already registered for given course. When i choose "Jeff Bezos" i should get error message but I get exception which says that is duplicate.
Parameterize the sql
Make the sql a string/text and use it
Get rid if bad associative join, create a INNER instead
use a using which implements idisposable
Assumptions since you did not post the source of the list
Broad assumption on the int vs string for id (int is most common so I go with that)
Suggest this might be refactored to methods for better testing
using System;
using System.Data.SqlClient;
// more here likely...
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Ceng.mdf;Integrated Security=True";
string getStudentIdSql = #"
SELECT s.StudentID
FROM Enrolment AS e
INNER JOIN Students AS s
ON e.StudentID = s.StudentID
AND E.CourseID = #CourseID
AND StudentName = #StudentName
";
int courseId = int.Parse(Request.QueryString["id"]); // consider tryparse here, I make assumptions on the int also
// string studentName = DropDownList1.SelectedItem.Value; // assumption if the values are there
string studentName = DropDownList1.SelectedItem.Text; // assumption based on code/comments, key part where it is defined is missing from question
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(getStudentIdSql, conn))
{
cmd.Parameters.Add("#CourseID", SqlDbType.Int).Value = courseId;
cmd.Parameters.Add("#StudentName", SqlDbType.VarChar, 80).Value = studentName;
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
/* if we wanted to have the rows
while (reader.Read())
{
Console.WriteLine($"{reader.GetInt32(0)}\t{ reader.GetString(1)}");
}
*/
Label1.Visible = true;
Label1.Text = "The selected student is already registered to the course!";
Label1.ForeColor = Color.Red;
}
/* basic thing
else
{
Console.WriteLine("No rows found.");
}
*/
else
{
Label1.Visible = true;
Label1.Text = "The selected student is succesfully registered!";
Label1.ForeColor = Color.Green;
SqlDataSource4.Insert();
GridView1.DataBind();
}
reader.Close();
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender,
EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Ceng.mdf;Integrated Security=True");
int selectedCourseId = 0;
string qs = Request.QueryString["id"];
int.TryParse(qs, out selectedCourseId);
string sv = DropDownList1.SelectedItem.Value;
SqlCommand cmd = new SqlCommand("Select * from Enrolment as e, Students as s where e.StudentID = s.StudentID and " +
"e.CourseID = #CourseID and s.StudentName = #StudentName", con);
cmd.Parameters.Add("#CourseID", SqlDbType.Int).Value = selectedCourseId;
cmd.Parameters.Add("#StudentName", SqlDbType.NVarChar).Value = sv;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if(reader.HasRows)
{
Label1.Visible = true;
Label1.Text = "The selected student is already registered to the course!";
Label1.ForeColor = Color.Red;
}
else
{
Label1.Visible = true;
Label1.Text = "The selected student is succesfully registered!";
Label1.ForeColor = Color.Green;
SqlDataSource4.Insert();
GridView1.DataBind();
}
reader.Close();
con.Close();
}

Adding data from SQL Server table into textbox when entering data in another textbox

Here is my program:
What I want to do: when I enter 1 in ProductID textbox, I want category, name and price for ProductID = 1 to be filled into their textboxes.
I have tried to read from product table where ProductID = ProductIDTB.Text and then changed the other textboxes to show the data inside the other columns
Here is my code when ProductID textbox is changed:
protected void ProductIDTB_TextChanged(object sender, EventArgs e)
{
string connectionString1;
SqlConnection cnn1;
connectionString1 = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Greenwich_Butchers;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
cnn1 = new SqlConnection(connectionString1);
string selectSql1 = "SELECT * FROM [Product] WHERE ProductID = ('" + Convert.ToInt32(ProductIDTB.Text) + "') ";
SqlCommand com1 = new SqlCommand(selectSql1, cnn1);
try
{
cnn1.Open();
using (SqlDataReader read = com1.ExecuteReader())
{
while (read.Read())
{
String productcategory = Convert.ToString(read["ProductCategory"]);
ProductCategoryTB.Text = productcategory;
String productname = Convert.ToString(read["ProductName"]);
ProductNameTB.Text = productname;
String productprice = Convert.ToString(read["ProductPrice"]);
ProdPriceTB.Text = productprice;
}
}
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
finally
{
cnn1.Close();
}
}
Work-around: as textbox_textchanged event was not working, I decided to add a button which finds product using the ID:
protected void FindProductBtn_Click(object sender, EventArgs e)
{
string connectionString1;
SqlConnection cnn1;
connectionString1 = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Greenwich_Butchers;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
cnn1 = new SqlConnection(connectionString1);
string selectSql1 = "SELECT * FROM [Product] WHERE ProductID = (" + Convert.ToInt32(ProductIDTB.Text) + ") ";
SqlCommand com1 = new SqlCommand(selectSql1, cnn1);
try
{
cnn1.Open();
using (SqlDataReader read = com1.ExecuteReader())
{
while (read.Read())
{
String productcategory = Convert.ToString(read["ProductCategory"]);
ProductCategoryTB.Text = productcategory;
String productname = Convert.ToString(read["ProductName"]);
ProductNameTB.Text = productname;
String productprice = Convert.ToString(read["ProductPrice"]);
ProdPriceTB.Text = productprice;
}
}
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
finally
{
cnn1.Close();
ProductCategoryTB.ReadOnly = true;
ProductNameTB.ReadOnly = true;
ProdPriceTB.ReadOnly = true;
}
}
Set the textbox's AutoPostBack attribute to true
More info: https://meeraacademy.com/textbox-autopostback-and-textchanged-event-asp-net/
<asp:TextBox ID="ProductIDTB" runat="server" AutoPostBack="True"
OnTextChanged="ProductIDTB_TextChanged"></asp:TextBox>
By the way, use SqlParameter to use parameterized query. Aside from sql-injection attack prevention, parameterized query can help the RDBMS store and re-use the execution plan of similar queries, to ensure better performance. See: https://dba.stackexchange.com/questions/123978/can-sp-executesql-be-configured-used-by-default
string selectSql1 = "SELECT * FROM [Product] WHERE ProductID = #productIdFilter";
int productIdFilter = Convert.ToInt32(ProductIDTB.Text);
SqlCommand com1 = new SqlCommand(selectSql1, cnn1);
com1.Parameters.AddWithValue("productIdFilter", productIdFilter);
OnTextChanged Event in Code Behind
protected void txtProductId_TextChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["_connect"].ToString());
int ProductId = Convert.ToInt32(txtProductId.Text);
SqlCommand com = con.CreateCommand();
com.CommandText = "sp_ProductGetData";
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Mode", 1);
com.Parameters.AddWithValue("#ProductId", ProductId);
con.Open();
SqlDataReader dr = com.ExecuteReader();
if (dr.HasRows)
{
dr.Read();
txtProductCategory.Text = Convert.ToString(dr["ProductCategory"]);
txtProductName.Text = Convert.ToString(dr["ProductName"]);
txtPrice.Text = Convert.ToString(dr["Price"]);
}
else
{
ScriptManager.RegisterClientScriptBlock((Page)(HttpContext.Current.Handler), typeof(Page), "alert", "javascript:alert('" + Convert.ToString(("No Record Found with Prodcut Id: "+ProductId)) + "');", true);
return;
}
con.Close();
}
Stored Procedure
CREATE PROCEDURE sp_ProductGetData
(
#Mode INT=NULL,
#ProductId INT=NULL
)
AS
BEGIN
IF(#Mode=1)
BEGIN
SELECT ProductCategory,ProductName,Price FROM Product
WHERE ProductId=#ProductId
END
END

dropdownlist not fetching values from table on OnSelectedIndexChanged

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

Table not updated in database after changing values from Textbox linked to Selected Item from ListView

This is how it works. I select a row from my listview then I will click "Edit" button which the values from the selected item will also be shown in the registration form. The "Register" button will now then changed to "Update". I am trying to update my customers table after changing inputs from the textboxes on my registration form but there are no changes in my database.
I receive no errors but I might have missed something here.
This is my code here:
private void btnRfrsh_Click(object sender, EventArgs e)
{
try
{
con = "datasource=localhost; port=3306; database=cam_air_db; uid=root;";
connect = new MySqlConnection(con);
connect.Open();
string query = "SELECT Cust_Lname, Cust_Fname, Cust_MI, Birthdate, Age, Sex, Passport_ID, Address, Contact_Num, Nationality from customers where removed = 0";
MySqlCommand select = new MySqlCommand(query, connect);
MySqlDataReader refresh = select.ExecuteReader();
while (refresh.Read())
{
ListViewItem item;
item = new ListViewItem(refresh.GetString(0));
item.SubItems.Add(refresh.GetString(1));
item.SubItems.Add(refresh.GetString(2));
item.SubItems.Add(refresh.GetString(3));
item.SubItems.Add(refresh.GetString(4));
item.SubItems.Add(refresh.GetString(5));
item.SubItems.Add(refresh.GetString(6));
item.SubItems.Add(refresh.GetString(7));
item.SubItems.Add(refresh.GetString(8));
item.SubItems.Add(refresh.GetString(9));
lviewCust.Items.Add(item);
}
if (refresh.Read())
{
connect.Close();
}
else
{
connect.Close();
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
private void btnEdit_Click(object sender, EventArgs e)
{
if (lviewCust.SelectedItems.Count > 0)
{
ListViewItem item = lviewCust.SelectedItems[0];
cust_fname.Text = item.SubItems[0].Text;
cust_lname.Text = item.SubItems[1].Text;
cust_mi.Text = item.SubItems[2].Text;
//DateTime bdate = Convert.ToDateTime(item.SubItems[3].Text);
String bdate_string = item.SubItems[3].Text;
DateTime bdate = DateTime.ParseExact(bdate_string, "dd-MM-yyyy", null);
cust_bdate.Value = bdate;
cust_age.Text = item.SubItems[4].Text;
cust_sex.Text = item.SubItems[5].Text;
cust_passid.Text = item.SubItems[6].Text;
cust_nation.Text = item.SubItems[9].Text;
cust_add.Text = item.SubItems[7].Text;
cust_contact.Text = item.SubItems[8].Text;
}
cust_fname.ReadOnly = true;
cust_lname.ReadOnly = true;
cust_mi.ReadOnly = true;
cust_passid.ReadOnly = true;
btnReg.Text = "Update";
btnReg.Name = "btnUpdate";
btnReg.Click -= this.btnReg_Click;
btnReg.Click += this.btnUpdate_Click;
}
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
con = "datasource=localhost; port=3306; database=cam_air_db; uid=root;";
connect = new MySqlConnection(con);
connect.Open();
string query = "UPDATE customers SET Age = '" + this.cust_age.Text + "', Nationality = '" + this.cust_nation.Text + "', Address = '" + this.cust_add.Text + "', Contact_Num = '" + this.cust_contact.Text + "' WHERE Cust_Fname = '" + this.cust_fname.Text + "' and Cust_Lname = '" + this.cust_lname.Text + "'";
MySqlCommand update = new MySqlCommand(query, connect);
MySqlDataReader updte = update.ExecuteReader();
MessageBox.Show("Customer Info Updated Successfully");
if (updte.Read())
{
connect.Close();
}
else
{
connect.Close();
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
cust_fname.Clear();
cust_lname.Clear();
cust_mi.Clear();
cust_bdate.Value = DateTime.Now;
cust_age.Clear();
cust_passid.Clear();
cust_add.Clear();
cust_contact.Clear();
cust_nation.Clear();
cust_fname.ReadOnly = false;
cust_lname.ReadOnly = false;
cust_mi.ReadOnly = false;
cust_passid.ReadOnly = false;
btnReg.Text = "Register";
btnReg.Name = "btnReg";
btnReg.Click -= this.btnUpdate_Click;
btnReg.Click += this.btnReg_Click;
}
}
}
First, I think you should use ExecuteNonQuery() instead of ExecuteReader().
You call ExecuteReader() when you execute a sql command that returns something (such as SELECT).
When you call a command that doesn't return anything (such as INSERT, UPDATE, DELETE, etc.), you should call ExecuteNonQuery().
See the details here.
Second, I think you should check the result before alert "successfully". ExecuteNonQuery() returns the number of rows affected, you can check this to determine success or not.

Obtaining data from table based on checkbox values

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
}

Categories

Resources