I have a form that has a asp.net gridview contained in it, on page load, I disabled some textboxes of the grid using jQuery.
my save method to the database is not working properly. I removed the grid from the "save" method and it works with the 2 textboxes.
protected void saverecords() {
try {
int suc = 0;
conn = new SqlConnection(connString);
conn.Open();
sqltrans = conn.BeginTransaction();
string sqldelete = "delete from TrainEmpha where TrainCode = '" + txtcode.Text.ToString().Trim() + "'";
SqlCommand comm = new SqlCommand(sqldelete, conn, sqltrans);
comm.ExecuteNonQuery();
comm.Dispose();
string insertgroup = " Insert into TrainEmpha (TrainCode, TrainDesc,disreglev,EmphaLevel,Award1,Award2,Award3,Award4)" +
" Values (#TrainCode, #TrainDesc,#disreglev,#EmphaLevel,#Award1,#Award2,#Award3,#Award4)";
foreach(GridViewRow gvr in gridview.Rows) {
string drplevel = ((DropDownList) gvr.FindControl("drp_grid_lvl")).Text.Trim();
string txttrain = ((TextBox) gvr.FindControl("txttrained")).Text.Trim();
string txtaward_1 = ((TextBox) gvr.FindControl("txtaward1")).Text.Trim();
string txtaward_2 = ((TextBox) gvr.FindControl("txtaward2")).Text.Trim();
string txtaward_3 = ((TextBox) gvr.FindControl("txtaward3")).Text.Trim();
string txtaward_4 = ((TextBox) gvr.FindControl("txtaward4")).Text.Trim();
comm = new SqlCommand(insertgroup, conn, sqltrans);
comm.Parameters.Add("#TrainCode", SqlDbType.VarChar);
comm.Parameters["#TrainCode"].Value = txtcode.Text.Trim();
comm.Parameters.Add("#TrainDesc", SqlDbType.VarChar);
comm.Parameters["#TrainDesc"].Value = txtdescrip.Text.Trim();
comm.Parameters.Add("#disreglev", SqlDbType.VarChar);
comm.Parameters["#disreglev"].Value = drplevel.Trim();
comm.Parameters.Add("#EmphaLevel", SqlDbType.VarChar);
comm.Parameters["#EmphaLevel"].Value = txttrain.Trim();
comm.Parameters.Add("#Award1", SqlDbType.VarChar);
comm.Parameters["#Award1"].Value = txtaward_1.Trim();
comm.Parameters.Add("#Award2", SqlDbType.VarChar);
comm.Parameters["#Award2"].Value = txtaward_2.Trim();
comm.Parameters.Add("#Award3", SqlDbType.VarChar);
comm.Parameters["#Award3"].Value = txtaward_3.Trim();
comm.Parameters.Add("#Award4", SqlDbType.VarChar);
comm.Parameters["#Award4"].Value = txtaward_4.Trim();
suc += comm.ExecuteNonQuery();
comm.Dispose();
}
if (suc > 0) {
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Notify", "alert(' RECORDS SAVED SUCCESSFULLY!');", true);
sqltrans.Commit();
} else {
lblDisplayErr.Text = "COULD NOT SAVE";
}
Related
I've a webform. On a dropdownlist selectedindexchanged event I run the given code to populate the form with details.
protected void ddlRequest_SelectedIndexChanged(object sender, EventArgs e)
{
if (IsPostBack)
{
string cs = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
using (SqlConnection conn = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("select * from tbl_Requests where RequestID = '" + ddlRequest.SelectedItem.Value + "'", conn);
SqlDataAdapter Adpt = new SqlDataAdapter();
DataSet dsrequest = new DataSet();
try
{
Adpt.SelectCommand = cmd;
Adpt.Fill(dsrequest);
foreach (DataRow dr in dsrequest.Tables[0].Rows)
{
string RequesterID = dsrequest.Tables[0].Rows[0]["RequesterID"].ToString();
string OrgID = dsrequest.Tables[0].Rows[0]["OrgID"].ToString();
string CaseID = dsrequest.Tables[0].Rows[0]["CaseID"].ToString();
string PatientFName = dsrequest.Tables[0].Rows[0]["PatientFName"].ToString();
string PatientLName = dsrequest.Tables[0].Rows[0]["PatientLName"].ToString();
string PatientAge = dsrequest.Tables[0].Rows[0]["PatientAge"].ToString();
string PatientGender = dsrequest.Tables[0].Rows[0]["PatientGender"].ToString();
string MedicalCondition = dsrequest.Tables[0].Rows[0]["MedicalCondition"].ToString();
string PatientMoNo = dsrequest.Tables[0].Rows[0]["PatientMoNo"].ToString();
string Remark = dsrequest.Tables[0].Rows[0]["Remark"].ToString();
string RequestStatus = dsrequest.Tables[0].Rows[0]["RequestStatus"].ToString();
ddlRequesterID.SelectedValue = RequesterID;
ddlOrgID.SelectedValue = OrgID;
txtCaseID.Text = CaseID;
txtPatientFName.Text = PatientFName;
txtPatientLName.Text = PatientLName;
txtPatientAge.Text = PatientAge;
txtPatientGender.Text = PatientGender;
txtMedicalCondition.Text = MedicalCondition;
txtPatientMoNo.Text = PatientMoNo;
txtRemark.Text = Remark;
ddlRequestStatus.SelectedValue = RequestStatus;
}
}
catch (Exception ex)
{
}
finally
{
}
}
}
}
Once user updates required fields on submit button click event I want to update the record with the values in various input fields.
with code given below.
protected void btnSubmitReq_Click(object sender, EventArgs e)
{
if (IsPostBack)
{
if (ddlRequest.SelectedValue == "0")
{
string cs = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
using (SqlConnection conn = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spInsRequests", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#RequesterID", SqlDbType.Int).Value = ddlRequesterID.SelectedValue;
cmd.Parameters.Add("#OrgID", SqlDbType.Int).Value = ddlOrgID.SelectedValue;
cmd.Parameters.Add("#CaseID", SqlDbType.NVarChar).Value = txtCaseID.Text;
cmd.Parameters.Add("#PatientFName", SqlDbType.NVarChar).Value = txtPatientFName.Text;
cmd.Parameters.Add("#PatientLName", SqlDbType.NVarChar).Value = txtPatientLName.Text;
cmd.Parameters.Add("#PatientAge", SqlDbType.NVarChar).Value = txtPatientAge.Text;
cmd.Parameters.Add("#PatientGender", SqlDbType.NVarChar).Value = txtPatientGender.Text;
cmd.Parameters.Add("#MedicalCondition", SqlDbType.NVarChar).Value = txtMedicalCondition.Text;
cmd.Parameters.Add("#PatientMoNo", SqlDbType.NVarChar).Value = txtPatientMoNo.Text;
cmd.Parameters.Add("#Remark", SqlDbType.NVarChar).Value = txtRemark.Text;
cmd.Parameters.Add("#RequestStatus", SqlDbType.NVarChar).Value = ddlRequestStatus.SelectedValue;
cmd.Parameters.Add("#strOwner", SqlDbType.VarChar).Value = User.Identity.Name;
cmd.Parameters.Add("#dbTstamp", SqlDbType.DateTime2).Value = DateTime.Now;
conn.Open();
cmd.ExecuteNonQuery();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
else
{
string cs = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
using (SqlConnection conn = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spUpdRequests", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#RequesterID", SqlDbType.Int).Value = Convert.ToInt32(ddlRequesterID.SelectedValue);
cmd.Parameters.Add("#OrgID", SqlDbType.Int).Value = Convert.ToInt32(ddlOrgID.SelectedValue);
cmd.Parameters.Add("#CaseID", SqlDbType.NVarChar).Value = txtCaseID.Text;
cmd.Parameters.Add("#PatientFName", SqlDbType.NVarChar).Value = txtPatientFName.Text;
cmd.Parameters.Add("#PatientLName", SqlDbType.NVarChar).Value = txtPatientLName.Text;
cmd.Parameters.Add("#PatientAge", SqlDbType.NVarChar).Value = txtPatientAge.Text;
cmd.Parameters.Add("#PatientGender", SqlDbType.NVarChar).Value = txtPatientGender.Text;
cmd.Parameters.Add("#MedicalCondition", SqlDbType.NVarChar).Value = txtMedicalCondition.Text;
cmd.Parameters.Add("#PatientMoNo", SqlDbType.NVarChar).Value = txtPatientMoNo.Text;
cmd.Parameters.Add("#Remark", SqlDbType.NVarChar).Value = txtRemark.Text;
cmd.Parameters.Add("#RequestStatus", SqlDbType.NVarChar).Value = ddlRequestStatus.SelectedValue;
cmd.Parameters.Add("#strOwner", SqlDbType.NVarChar).Value = User.Identity.Name;
cmd.Parameters.Add("#dbTstamp", SqlDbType.DateTime2).Value = DateTime.Now;
cmd.Parameters.Add("#Original_RequestID", SqlDbType.Int).Value = Convert.ToInt32(ddlRequest.SelectedValue);
cmd.Parameters.Add("#RequestID", SqlDbType.Int).Value = Convert.ToInt32(ddlRequest.SelectedValue);
conn.Open();
cmd.ExecuteNonQuery();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
}
}
This doesn't update the record.
Pls help.
Resolved.
I was putting EnableViewState="false" in ddlRequest which was causing this issue. I removed it. Now everything working fine.
Thanks.
How to achieve the requirements below:
The Retrieve button click event:
if user doesn't enter CustID in txtCustID need to inform them to enter Customer Id via lblMessage;
if entered CustId doesn't exist in database inform user that it doesn't exist via lblMessage.
The Update button click event - need to ensure that Customer ID already exists in the database.
The Delete button click event: same requirements as for Retrieve button.
I must use error/exception handling (try-catch) to achieve these (project requirement). I spent hours trying, but no success. I would be very grateful for some help! My code is below:
namespace ACME
{
public partial class Customer : System.Web.UI.Page
{
SqlConnection conn;
SqlDataAdapter adapter = new SqlDataAdapter();
DataTable table = new DataTable();
SqlCommand command = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
}
private void Page_PreInit(object sender, EventArgs e)
{
HttpCookie setTheme = Request.Cookies.Get("UserSelectedTheme");
if (setTheme != null)
{
Page.Theme = setTheme.Value;
}
}
protected void Clear()
{
txtCustID.Text = "";
txtFirstname.Text = "";
txtSurname.Text = "";
rbtGender.SelectedValue = "";
txtAge.Text = "";
txtAddress1.Text = "";
txtAddress2.Text = "";
txtCity.Text = "";
txtPhone.Text = "";
txtMobile.Text = "";
txtEmail.Text = "";
txtEmail2.Text = "";
}
protected void btnNew_Click(object sender, EventArgs e)
{
SqlDataAdapter adapter1 = new SqlDataAdapter();
DataTable table1 = new DataTable();
SqlCommand command1 = new SqlCommand();
Clear();
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
command1.Connection = conn;
command1.CommandType = CommandType.StoredProcedure;
command1.CommandText = "LargestCustID";
command1.Connection.Open();
int id = (int)command1.ExecuteScalar() + 1;
txtCustID.Text = id.ToString();
command1.Dispose();
conn.Close();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "AddCustomer";
command.Connection.Open();
command.Parameters.AddWithValue("#CustID",
int.Parse(txtCustID.Text));
command.Parameters.AddWithValue("#Firstname", txtFirstname.Text);
command.Parameters.AddWithValue("#Surname", txtSurname.Text);
command.Parameters.AddWithValue("#Gender", rbtGender.SelectedValue);
command.Parameters.AddWithValue("#Age", int.Parse(txtAge.Text));
command.Parameters.AddWithValue("#Address1", txtAddress1.Text);
command.Parameters.AddWithValue("#Address2", txtAddress2.Text);
command.Parameters.AddWithValue("#City", txtCity.Text);
command.Parameters.AddWithValue("#Phone", txtPhone.Text);
command.Parameters.AddWithValue("#Mobile", txtMobile.Text);
command.Parameters.AddWithValue("#Email", txtEmail.Text);
adapter.InsertCommand = command;
adapter.InsertCommand.ExecuteNonQuery();
lblMessage.Text = "The new record has been added to the database!";
command.Connection.Close();
Clear();
}
protected void btnRetrieve_Click(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "GetCustID";
command.Connection.Open();
SqlParameter param = new SqlParameter();
param.ParameterName = "#CustID";
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Input;
param.Value = int.Parse(txtCustID.Text);
command.Parameters.Add(param);
adapter.SelectCommand = command;
adapter.Fill(table);
int id = table.Rows.Count;
if (id == 0)
{
lblMessage.Text = "Customer ID does not exists!";
}
else
{
lblMessage.Text = "";
txtFirstname.Text = table.Rows[0].Field<string>("Firstname");
txtFirstname.DataBind();
txtSurname.Text = table.Rows[0].Field<string>("Surname");
txtSurname.DataBind();
txtAge.Text = table.Rows[0].Field<int>("Age").ToString();
txtAge.DataBind();
txtAddress1.Text = table.Rows[0].Field<string>("Address1");
txtAddress1.DataBind();
txtAddress2.Text = table.Rows[0].Field<string>("Address2");
txtAddress2.DataBind();
txtCity.Text = table.Rows[0].Field<string>("City");
txtCity.DataBind();
txtPhone.Text = table.Rows[0].Field<string>("Phone");
txtPhone.DataBind();
txtMobile.Text = table.Rows[0].Field<string>("Mobile");
txtMobile.DataBind();
txtEmail.Text = table.Rows[0].Field<string>("Email");
txtEmail.DataBind();
}
command.Connection.Close();
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "UpdateCustomer";
command.Connection.Open();
command.Parameters.AddWithValue("#CustID",
int.Parse(txtCustID.Text));
command.Parameters.AddWithValue("#Firstname", txtFirstname.Text);
command.Parameters.AddWithValue("#Surname", txtSurname.Text);
command.Parameters.AddWithValue("#Gender", rbtGender.SelectedValue);
command.Parameters.AddWithValue("#Age", int.Parse(txtAge.Text));
command.Parameters.AddWithValue("#Address1", txtAddress1.Text);
command.Parameters.AddWithValue("#Address2", txtAddress2.Text);
command.Parameters.AddWithValue("#City", txtCity.Text);
command.Parameters.AddWithValue("#Phone", txtPhone.Text);
command.Parameters.AddWithValue("#Mobile", txtMobile.Text);
command.Parameters.AddWithValue("#Email", txtEmail.Text);
lblMessage.Text = "The record has been updated!";
command.Connection.Close();
Clear();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "DeleteCustomer";
command.Connection.Open();
SqlParameter param = new SqlParameter();
param.ParameterName = "#CustID";
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Input;
param.Value = int.Parse(txtCustID.Text);
command.Parameters.Add(param);
adapter.DeleteCommand = command;
adapter.DeleteCommand.ExecuteNonQuery();
int id = (int)param.Value;
command.Connection.Close();
}
catch (Exception ex)
{
lblMessage.Text += "Please enter Customer ID!";
}
try
{
lblMessage.Text = "";
SqlParameter param = new SqlParameter();
param.ParameterName = "#CustID";
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Input;
param.Value = int.Parse(txtCustID.Text);
command.Parameters.Add(param);
adapter.DeleteCommand = command;
adapter.DeleteCommand.ExecuteNonQuery();
int id = table.Rows.Count;
id = (int)param.Value;
lblMessage.Text += "Customer record has been deleted";
command.Connection.Close();
}
catch (Exception ex)
{
lblMessage.Text = "Customer ID doesnot exists!";
}
Clear();
}
public string CustID { get; set; }
}
}
It sounds like you are trying to control flow of your application by use of exceptions. There are many reasons against this approach:
1) Code is difficult to understand and to debug.
2) Throwing exceptions in .Net is expensive.
3) If exception control flow of application how do you differentiate them from a real exceptions (thrown when something doesn't work as expected)?
If, on the other hand, you want to throw an exception when any of the scenarios you listed in the question happens then you can use standard .Net Exception class:
if (string.IsNullOrWhiteSpace(txtCustID.Text))
{
throw new Exception("Id not provided.");
}
Or you can create a custom exception to provide some more specific information:
public class IdNotProvidedException : Exception
{
public string MyCommandName { get; set; }
public IdNotProvidedException(string msg)
: base(msg)
{
}
public IdNotProvidedException(string msg, string myCommandName)
: base(msg)
{
this.MyCommandName = myCommandName;
}
}
And then you initialize and throw your custom exception.
Lastly, there are already places in your code, though not mentioned in your question, that are worth wrapping in a try...catch block. Basically, any place where you connect with the server may result in something unexpected (for instance, the server may not be available).
I have a textbox and a button that search. Once I type something in the textbox and clicked searched, the gridview will display all the records. The problem is if I enter nothing in the textbox and click search, it will give me all the records. I want it to give me record not found if nothing is enter in the textbox when search.
protected void SearchBlog(object sender, EventArgs e)
{
String ConStr = ConfigurationManager.ConnectionStrings["BlogConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(ConStr);
try
{
string invalid = txtSearch.Text;
String SQL = null;
if (invalid == "all")
{
SQL = "SELECT BlogID, AdminNumber, Name, Description FROM [EntryTable]";
}
else
{
SQL = "SELECT BlogID, AdminNumber, Name, Description FROM [EntryTable] WHERE AdminNumber LIKE #searchAdminNumber OR BlogType LIKE #searchBlogType OR Name LIKE #searchName";
}
SqlCommand cmd = new SqlCommand(SQL, con);
con.Open();
cmd.Parameters.Add("#searchBlogType", SqlDbType.NVarChar, 50);
cmd.Parameters["#searchBlogType"].Value = txtSearch.Text + "%";
cmd.Parameters.Add("#searchName", SqlDbType.NVarChar, 50);
cmd.Parameters["#searchName"].Value = txtSearch.Text + "%";
cmd.Parameters.Add("#searchAdminNumber", SqlDbType.NVarChar, 50);
cmd.Parameters["#searchAdminNumber"].Value = txtSearch.Text + "%";
SqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
grdResult.DataSource = dt;
grdResult.DataBind();
lblError.Text = "";
if (dt.Rows.Count > 0)
{
lblError.Text = null;
}
else
{
lblError.Text = "Record not found";
}
reader.Close();
}
catch (Exception)
{
lblError.Text = "Error!";
//lblOrderError.Text = ex.Message;
}
finally
{
con.Close();
}
}
private void bindResultGridView()
{
String ConStr = ConfigurationManager.ConnectionStrings["BlogConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(ConStr);
try
{
string invalid = txtSearch.Text;
String SQL = null;
if (invalid == "all")
{
SQL = "SELECT BlogID, AdminNumber, Name, Description FROM [EntryTable]";
}
else
{
SQL = "SELECT BlogID, AdminNumber, Name, Description FROM [EntryTable] WHERE AdminNumber LIKE #searchAdminNumber OR BlogType LIKE #searchBlogType OR Name LIKE #searchName";
}
SqlCommand cmd = new SqlCommand(SQL, con);
con.Open();
cmd.Parameters.Add("#searchBlogType", SqlDbType.NVarChar, 50);
cmd.Parameters["#searchBlogType"].Value = txtSearch.Text;
cmd.Parameters.Add("#searchName", SqlDbType.NVarChar, 50);
cmd.Parameters["#searchName"].Value = txtSearch.Text;
cmd.Parameters.Add("#searchAdminNumber", SqlDbType.NVarChar, 50);
cmd.Parameters["#searchAdminNumber"].Value = txtSearch.Text;
SqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
grdResult.DataSource = dt;
grdResult.DataBind();
lblError.Text = "";
reader.Close();
}
catch (SqlException ex)
{
lblError.Text = "Error:" + ex.Message.ToString();
}
finally
{
con.Close();
}
}
protected void grdResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
int newPageIndex = e.NewPageIndex;
grdResult.PageIndex = newPageIndex;
bindResultGridView();
}
Edited this works
protected void SearchBlog(object sender, EventArgs e)
{
String ConStr = ConfigurationManager.ConnectionStrings["BlogConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(ConStr);
try
{
string invalid = txtSearch.Text;
String SQL = null;
if (invalid == "")
{
SQL = "SELECT * FROM [EntryTable] WHERE BlogID=-1";
}
else if (invalid == "all")
{
SQL = "SELECT BlogID, AdminNumber, Name, Description FROM [EntryTable]";
}
else
{
SQL = "SELECT BlogID, AdminNumber, Name, Description FROM [EntryTable] WHERE AdminNumber LIKE #searchAdminNumber OR BlogType LIKE #searchBlogType OR Name LIKE #searchName";
}
SqlCommand cmd = new SqlCommand(SQL, con);
con.Open();
cmd.Parameters.Add("#searchBlogType", SqlDbType.NVarChar, 50);
cmd.Parameters["#searchBlogType"].Value = txtSearch.Text + "%";
cmd.Parameters.Add("#searchName", SqlDbType.NVarChar, 50);
cmd.Parameters["#searchName"].Value = txtSearch.Text + "%";
cmd.Parameters.Add("#searchAdminNumber", SqlDbType.NVarChar, 50);
cmd.Parameters["#searchAdminNumber"].Value = txtSearch.Text + "%";
SqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
grdResult.DataSource = dt;
grdResult.DataBind();
lblError.Text = "";
if (dt.Rows.Count > 0)
{
lblError.Text = null;
}
else
{
lblError.Text = "Record not found";
}
reader.Close();
}
catch (Exception)
{
lblError.Text = "Error!";
//lblOrderError.Text = ex.Message;
}
finally
{
con.Close();
}
}
You probably want something like this:
string searchString = txtSearch.Text;
if (!string.IsNullOrWhiteSpace(searchString))
{
// your search logic here
}
else
{
// inform user of invalid search string / do nothing / whatever
}
If it's not valid to search on an empty string, it's probably better simply not to search if one is provided.
I think, you are hitting the database unnecessarily, even if the textbox is empty.
You should check first if the textbox is not empty. If it is empty or null, let the user know that the search field is empty OR You can use RequiredField validator on the textbox so that when they click the Search button without any data in the text, the user will be notified with a error message saying, box cannot be empty.
<asp:TextBox runat="server" id="txtSearch" />
<asp:RequiredFieldValidator runat="server" id="reqName" controltovalidate="txtSearch" errormessage="Field cannot be empty!" />
Hope this helps !!
this is my code,when the textbox content changes the datas required have to retrieved from the databse and displayed in the labels specified.
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Match match = Regex.Match(TextBox1.Text, #"^\d{4}[A-Z]{5}\d{3}$");
if (match.Success)
{
try
{
DropDownList1.Focus();
string dpt = (string)Session["deptmnt"];
idd = TextBox1.Text;
Label33.Text = idd;
string val = idd;
string con = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
SqlConnection con1 = new SqlConnection(con);
con1.Open();
// string val1 = dpt;
try
{
String str = "SELECT * from student where sid=#val";
SqlCommand cmd = new SqlCommand(str, con1);
cmd.CommandType = CommandType.Text;
SqlParameter sql;
cmd.Parameters.Clear();
sql = cmd.Parameters.Add("#val", SqlDbType.VarChar, 20);
sql.Value = val;
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows == false)
{
Label35.Visible = true;
TextBox1.Text = "";
}
else
{
{
Panel3.Visible = true;
DropDownList1.Focus();
while (reader.Read()) // if can read row from database
{
Panel3.Visible = true;
Label3.Text = reader["sname"].ToString();
Label5.Text = reader["dept"].ToString();
Label25.Text = reader["yr"].ToString();
}
cmd.Parameters.Clear();
{
string val1 = idd;
string str2 = "SELECT bid from studentissuebook where sid=#val1 AND status='" + "lost" + "'";
SqlCommand cmd2 = new SqlCommand(str2, con1);
cmd2.CommandType = CommandType.Text;
cmd2.Parameters.Clear();
SqlParameter sql2;
sql2 = cmd2.Parameters.Add("#val1", SqlDbType.VarChar, 20);
sql2.Value = val1;
SqlDataReader reader1 = cmd2.ExecuteReader();
if (reader1.HasRows == false)
{
TextBox1.Text = "";
Label39.Visible = true;
Panel3.Visible = false;
}
else
{
DropDownList1.Focus();
while (reader1.Read()) // if can read row from database
{
DropDownList1.Items.Add(reader1[0].ToString());
}
DropDownList1.Focus();
}
}
}
}
con1.Close();
}
catch(Exception ex)
{
TextBox1.Text=ex.ToString();
}
}
catch (Exception ex)
{
TextBox1.Text = ex.ToString();
}
} else
{
formatlabel.Visible = true;
}
}
but,when i run the code,i get an error "The variable name '#sid' has already been declared. Variable names must be unique within a query batch or stored procedure.",I googled, generally this error occurs when there is a for loop or any loops,but i do not have any loops in my code.so im unable to find the cause
Try using two separate connection and command objects, like this:
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Match match = Regex.Match(TextBox1.Text, #"^\d{4}[A-Z]{5}\d{3}$");
if (match.Success)
{
DropDownList1.Focus();
string dpt = (string) Session["deptmnt"];
idd = TextBox1.Text;
Label33.Text = idd;
string val = idd;
string con = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
using (SqlConnection con1 = new SqlConnection(con))
{
String str = "SELECT * from student where sid=#val";
con1.Open();
using (SqlCommand cmd = new SqlCommand(str, con1))
{
cmd.CommandType = CommandType.Text;
SqlParameter sql;
cmd.Parameters.Clear();
sql = cmd.Parameters.Add("#val", SqlDbType.VarChar, 20);
sql.Value = val;
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows == false)
{
Label35.Visible = true;
TextBox1.Text = "";
}
else
{
Panel3.Visible = true;
DropDownList1.Focus();
while (reader.Read()) // if can read row from database
{
Panel3.Visible = true;
Label3.Text = reader["sname"].ToString();
Label5.Text = reader["dept"].ToString();
Label25.Text = reader["yr"].ToString();
}
cmd.Parameters.Clear();
}
}
}
using (SqlConnection con2 = new SqlConnection(con))
{
string val1 = idd;
string str2 = "SELECT bid from studentissuebook where sid=#val1 AND status='" + "lost" + "'";
con2.Open();
using (SqlCommand cmd2 = new SqlCommand(str2, con2))
{
cmd2.CommandType = CommandType.Text;
cmd2.Parameters.Clear();
SqlParameter sql2;
sql2 = cmd2.Parameters.Add("#val1", SqlDbType.VarChar, 20);
sql2.Value = val1;
SqlDataReader reader1 = cmd2.ExecuteReader();
if (reader1.HasRows == false)
{
TextBox1.Text = "";
Label39.Visible = true;
Panel3.Visible = false;
}
else
{
DropDownList1.Focus();
while (reader1.Read()) // if can read row from database
{
DropDownList1.Items.Add(reader1[0].ToString());
}
DropDownList1.Focus();
}
}
}
}
else
{
formatlabel.Visible = true;
}
}
Note: I have removed your try-catch blocks to make the code simpler to interpret, once it is working, then please re-apply your try-catch logic where you feel appropriate. Also, I added using blocks for the SqlConnection and SqlCommand objects, this will clean up the connection even if an exception happens.
I have a DropDownList control in ItemTemplate of FormView_Product, how do I modify the code below to reference to my DropDownList1?
String strQty = DropDownList1.Items[DropDownList1.SelectedIndex].ToString();
Code
}
protected void btnBuy_Click(Object sender, EventArgs e)
{
// test to remind customer to login first
if ((string)Session["sFlag"] != "T")
{
Type csType = this.GetType();
ClientScript.RegisterStartupScript(csType, "Error", scriptErrorLogin);
}
else
{
// test to remind customer to login first
if ((string)Session["sFlag"] != "T")
{
Type csType = this.GetType();
ClientScript.RegisterStartupScript(csType, "Error", scriptErrorLogin);
}
else
{
OleDbConnection mDB = new OleDbConnection();
mDB.ConnectionString = "Provider = Microsoft.Jet.OLEDB.4.0;Data source="
+ Server.MapPath("~/App_Data/webBase.mdb");
OleDbCommand cmd;
//insert item purchased to itemsTable
int intOrderNo = (int)Session["sOrderNo"];
FormViewRow row0 = FormView_Product.Row;
String strProductId = ((Label)row0.FindControl("lblProductId")).Text;
Int32 unitPrice = Convert.ToInt32(((Label)row0.FindControl("lblUnitPrice")).Text);
float floUnitPrice = float.Parse(strUnitPrice);
String strQty = DropDownList1.Items[DropDownList1.SelectedIndex].ToString();
int intQty = int.Parse(strQty);
string strSQL = "INSERT INTO itemsTable(iOrderNo, iProductId, iQty, iUnitPrice)"
+ "VALUES (#OrderNo, #ProductId, #Qty, #UnitPrice)";
cmd = new OleDbCommand(strSQL, mDB);
cmd.Parameters.AddWithValue("#OrderNO", intOrderNo);
cmd.Parameters.AddWithValue("#ProductId", strProductId);
cmd.Parameters.AddWithValue("#Qty", intQty);
cmd.Parameters.AddWithValue("#UnitPrice", floUnitPrice);
mDB.Open();
cmd.ExecuteNonQuery();
mDB.Close();
Response.Redirect("ShoppingCart.aspx");
}
}
}
Try This
DropDownList DropDownList1 = (DropDownList)FormView_Product.FindControl("DropDownList1");
String strQty = DropDownList1.SelectedValue;