Textbox retains old value before the update process asp.net - c#

The problem is, that I am trying to update my database record trough user's input on a Textbox.
The code below shows
protected void Page_Load(object sender, EventArgs e)
{
con1.Open();
try
{
//btn_save.Click += new EventHandler(btn_save_Click);
rs_id = Session["Res_Id"].ToString();
if (!this.IsPostBack)
{
getcategory();
getcuisine();
}
try
{
sitem_id = Session["item_id"].ToString();
if (sitem_id != "")
{
getitemdata();
getaddonprice();
getchoiceprice();
}
}
catch(Exception ex)
{
}
}
catch (Exception ex)
{
Response.Redirect("Default");
}
}
public void getitemdata()
{
try
{
SqlCommand cmd = new SqlCommand("select * from tbl_item where item_id='" + sitem_id + "'", con1);
SqlDataReader dr = cmd.ExecuteReader();
if(dr.Read())
{
string price,status;
txt_iname.Text = dr["item_name"].ToString();
txt_desc.Text = dr["item_description"].ToString();
drp_category.SelectedValue = dr["category_id"].ToString();
cui_drp.SelectedValue = dr["cusine_id"].ToString();
price_chk = dr["pos"].ToString();
status = dr["status"].ToString();
img_nname = dr["item_uname"].ToString();
img_dname = dr["item_img"].ToString();
if (price_chk == "1")
{
chk_price.Checked = true;
div_price.Style["display"] = "none";
div_choice.Style["display"] = "block";
div_addon.Style["display"] = "block";
}
else
{
chk_price.Checked = false;
div_price.Style["display"] = "block";
div_choice.Style["display"] = "none";
div_addon.Style["display"] = "none";
}
if(status=="1")
{
chk_status.Checked = true;
}
else
{
chk_status.Checked = false;
}
update_id = "1";
}
dr.Close();
}
catch(Exception ex)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", ex.ToString(), true);
}
}
public void getaddonprice()
{
try
{
SqlCommand cmd = new SqlCommand("select vname as add_on_name,price as amt from tbl_price_master where item_id='" + sitem_id + "' and type='2'", con1);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
grid_addon.DataSource = dt;
grid_addon.DataBind();
}
catch(Exception ex)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", ex.ToString(), true);
}
}
public void getchoiceprice()
{
try
{
SqlCommand cmd = new SqlCommand("select vname as choice_name,price as amt from tbl_price_master where item_id='" + sitem_id + "' and type='1'", con1);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
grid_choice.DataSource = dt;
grid_choice.DataBind();
}
catch (Exception ex)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", ex.ToString(), true);
}
}
public void update()
{
try
{
string ch_status;
if(chk_status.Checked)
{
ch_status = "1";
}
else
{
ch_status = "0";
}
string item_uname = txt_iname.Text + "_" + rs_id;
if (chk_price.Checked == true)
{
if(img_res.HasFile)
{
deleteimg();
getimg();
SqlCommand cmd = new SqlCommand("master_crud_b2b", con1);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#item_name", txt_iname.Text);
cmd.Parameters.AddWithValue("#restaurant_id", rs_id);
cmd.Parameters.AddWithValue("#cuisine_id", cui_drp.SelectedValue.ToString());
cmd.Parameters.AddWithValue("#category_id", drp_category.SelectedValue.ToString());
cmd.Parameters.AddWithValue("#item_img", "Item_Images/" + newFileName);
cmd.Parameters.AddWithValue("#pos", "1");
cmd.Parameters.AddWithValue("#status", ch_status);
cmd.Parameters.AddWithValue("#item_desc", txt_desc.Text);
cmd.Parameters.AddWithValue("#item_uname", item_uname);
cmd.Parameters.AddWithValue("#item_id", sitem_id);
cmd.Parameters.AddWithValue("#mode", 21);
cmd.ExecuteNonQuery();
item_id = sitem_id;
deleteprice();
price_insert();
price_insert2();
}
else
{
SqlCommand cmd = new SqlCommand("master_crud_b2b", con1);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#item_name", txt_iname.Text);
cmd.Parameters.AddWithValue("#restaurant_id", rs_id);
cmd.Parameters.AddWithValue("#cuisine_id", cui_drp.SelectedValue.ToString());
cmd.Parameters.AddWithValue("#category_id", drp_category.SelectedValue.ToString());
cmd.Parameters.AddWithValue("#pos", "1");
cmd.Parameters.AddWithValue("#status", ch_status);
cmd.Parameters.AddWithValue("#item_desc", txt_desc.Text);
cmd.Parameters.AddWithValue("#item_uname", item_uname);
cmd.Parameters.AddWithValue("#item_id", sitem_id);
cmd.Parameters.AddWithValue("#mode", 20);
cmd.ExecuteNonQuery();
item_id = sitem_id;
deleteprice();
price_insert();
price_insert2();
}
}
else
{
if (img_res.HasFile)
{
deleteimg();
getimg();
SqlCommand cmd = new SqlCommand("master_crud_b2b", con1);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#item_name", txt_iname.Text);
cmd.Parameters.AddWithValue("#restaurant_id", rs_id);
cmd.Parameters.AddWithValue("#cuisine_id", cui_drp.SelectedValue.ToString());
cmd.Parameters.AddWithValue("#category_id", drp_category.SelectedValue.ToString());
cmd.Parameters.AddWithValue("#item_img", "Item_Images/" + newFileName);
cmd.Parameters.AddWithValue("#pos", "0");
cmd.Parameters.AddWithValue("#status", ch_status);
cmd.Parameters.AddWithValue("#item_desc", txt_desc.Text);
cmd.Parameters.AddWithValue("#item_uname", item_uname);
cmd.Parameters.AddWithValue("#item_id", sitem_id);
cmd.Parameters.AddWithValue("#mode", 21);
cmd.ExecuteNonQuery();
item_id = sitem_id;
deleteprice();
price_insert3();
}
else
{
SqlCommand cmd = new SqlCommand("master_crud_b2b", con1);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#item_name", txt_iname.Text);
cmd.Parameters.AddWithValue("#restaurant_id", rs_id);
cmd.Parameters.AddWithValue("#cuisine_id", cui_drp.SelectedValue.ToString());
cmd.Parameters.AddWithValue("#category_id", drp_category.SelectedValue.ToString());
cmd.Parameters.AddWithValue("#pos", "0");
cmd.Parameters.AddWithValue("#status", ch_status);
cmd.Parameters.AddWithValue("#item_desc", txt_desc.Text);
cmd.Parameters.AddWithValue("#item_uname", item_uname);
cmd.Parameters.AddWithValue("#item_id", sitem_id);
cmd.Parameters.AddWithValue("#mode", 20);
cmd.ExecuteNonQuery();
item_id = sitem_id;
deleteprice();
price_insert3();
}
}
Session["item_id"] = null;
update_id = "0";
Response.Redirect("Item_List");
}
catch (Exception ex)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", ex.ToString(), true);
}
}
Now, just to make sure that all is ok, I tried changing the content of the Textbox named txt_desc. To my surprise, upon clicking the save button the content of the txt_desc Textbox returns to its original content.
Thank you.

Function getitemdata(); is always called. It should be only called on first load of page.
When button is clicked, the data from database is filled again in text_desc by this function.
You should move all code that fills data in input fields from database in !IsPostback
Like
In your page_load()
if (!this.IsPostBack)
{
getcategory();
getcuisine();
getitemdata();
}
Also note following:
Using connection object as global class variable can give you connection management troubles at some point. Move it closer to SqlCommand usage.
Your code is vulnerable to SqlInjection attack. Use #variables instead of string concatenation for SQL query in SqlCommand

Related

SQL commands not working in C# (ASP.NET web forms)

I'm having a trouble with my code.
I'm trying to have the user the ability to submit his email to subscribe to my "notify me" service, I havn't code anything lately so I a bit confused..
I'm trying to Insert, Read, and Update data in my Online SQL Server.. but nothing seems to work! I don't know why I tried everything I know I check a million times it seems good.
Plus if there is any errors my catch should show it to me but even that doesn't work :(
Take a look at this maybe your eyes will see something I don't see.
protected void btnSubmit_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["notifyCS"].ConnectionString;
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
try
{
string checkEmail = "SELECT User_Email FROM tbl_users WHERE User_Email = #User_Email";
string checkSubscription = "SELECT User_Status FROM tbl_users WHERE User_Email = #User_Email";
string submitEmail = "INSERT INTO tbl_users (User_UID, User_Email, User_Status) VALUES (#User_UID, #User_Email, #User_Status)";
string submitEmail2 = "UPDATE tbl_users SET User_UID = #User_UID, User_Status = #User_Status WHERE User_Email = #User_Email";
SqlCommand emailCMD = new SqlCommand(checkEmail, conn);
SqlDataAdapter emailSDA = new SqlDataAdapter
{
SelectCommand = emailCMD
};
DataSet emailDS = new DataSet();
emailSDA.Fill(emailDS);
//if there is no email registered.
if (emailDS.Tables[0].Rows.Count == 0)
{
SqlCommand registerEmail = new SqlCommand(submitEmail, conn);
string User_UID = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
registerEmail.Parameters.AddWithValue("#User_UID", HttpUtility.HtmlEncode(User_UID));
registerEmail.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
registerEmail.Parameters.AddWithValue("#User_Status", HttpUtility.HtmlEncode("subscribed"));
registerEmail.ExecuteNonQuery();
registerEmail.Dispose();
conn.Close();
conn.Dispose();
email.Text = null;
}
else if (emailDS.Tables[0].Rows.Count > 0)
{
using (SqlCommand checkSub = new SqlCommand(checkSubscription, conn))
{
checkSub.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
SqlDataReader sdr = checkSub.ExecuteReader();
if (sdr.HasRows)
{
string res = sdr["User_Status"].ToString();
if (res != "subscribed")
{
using (SqlCommand registerEmail2 = new SqlCommand(submitEmail2, conn))
{
string User_UID = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
registerEmail2.Parameters.AddWithValue("#User_UID", HttpUtility.HtmlEncode(User_UID));
registerEmail2.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
registerEmail2.Parameters.AddWithValue("#User_Status", HttpUtility.HtmlEncode("subscribed"));
registerEmail2.ExecuteNonQuery();
registerEmail2.Dispose();
conn.Close();
conn.Dispose();
email.Text = null;
}
}
else
{
conn.Close();
conn.Dispose();
Response.Redirect("index.aspx");
}
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
conn.Close();
if (conn.State != ConnectionState.Closed)
{
conn.Close();
conn.Dispose();
}
}
}
}
Try it this way:
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
string checkEmail = "SELECT * FROM tbl_users WHERE User_Email = #User";
SqlCommand emailCMD = new SqlCommand(checkEmail, conn);
emailCMD.Parameters.Add("#User", SqlDbType.NVarChar).Value = email.Text;
SqlDataAdapter da = new SqlDataAdapter(emailCMD);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
DataTable emailRecs = new DataTable();
emailRecs.Load(emailCMD.ExecuteReader());
DataRow OneRec;
if (emailRecs.Rows.Count == 0)
{
OneRec = emailRecs.NewRow();
emailRecs.Rows.Add(OneRec);
}
else
{
// record exists
OneRec = emailRecs.Rows[0];
}
// modify reocrd
OneRec["User_UID"] = User_UID;
OneRec["User_Email"] = email.Text;
OneRec["User_Status"] = "subscribed";
email.Text = null;
da.Update(emailRecs);
}
}

C# update code for logout using mysql

im doing an update statement where the datetimepicker(logout) will insert into the same row as login but its making another row when i logout here is the link : http://imgur.com/a/rAWhi
ps. the problem here is the logout button is inserting into another row.. but i want to insert it in the same row.
here is my code :
private void button1_Click(object sender, EventArgs e)
{
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from empinfo where username = '" + label4.Text + "' and IDNUMBER = '" + textBox1.Text + "' ";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
i = Convert.ToInt32(dt.Rows.Count.ToString());
if (string.IsNullOrEmpty(textBox1.Text))
{
MessageBox.Show("Input your id number");
}
else if (i == 0)
{
MessageBox.Show("Username and IDNUMBER didn't match.", "Log-In Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
updateuser();
login frmm = new login();
frmm.Show();
this.Close();
}
con.Close();
}
public void updateuser()
{
MySqlConnection cnn = new MySqlConnection(mysqlAddress);
MySqlCommand cmdupdate;
cnn.Open();
try
{
cmdupdate = cnn.CreateCommand();
cmdupdate.CommandText = "update employee set logout = #logout";
cmdupdate.CommandText = "Insert into employee (logout) values (#logout)";
cmdupdate.Parameters.AddWithValue("#logout", dateTimePicker1.Value);
cmdupdate.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (cnn.State == ConnectionState.Open)
{
cnn.Close();
MessageBox.Show("Data has been saved");
}
}
}
As #Ben in the comments pointed out, you do not need to use insert and only want update so change your code like this:
try
{
cmdupdate = cnn.CreateCommand();
cmdupdate.CommandText = "update employee set logout=#logout";
cmdupdate.CommandText += "WHERE IDNUMBER=#IDNUMBER";
cmdupdate.Parameters.AddWithValue("#IDNUMBER", textBox1.Text.Trim());
cmdupdate.Parameters.AddWithValue("#logout", dateTimePicker1.Value);
cmdupdate.ExecuteNonQuery();
}
The Where is to make sure it only updates the IDNUMBER on the textbox.
I think you should create different methods for login and logout like
For LOGIN
public static long id;
public void loginuser()
{
MySqlConnection cnn = new MySqlConnection(mysqlAddress);
MySqlCommand cmd;
cnn.Open();
try
{
cmd = cnn.CreateCommand();
cmd.CommandText = "Insert into employee (logout) values (#logout)";
cmd.Parameters.AddWithValue("#login", DateTime.Now);
cmd.ExecuteNonQuery();
id = cmd.LastInsertedId; // it will return the id of last inserted row
}
catch (Exception)
{
throw;
}
finally
{
if (cnn.State == ConnectionState.Open)
{
cnn.Close();
MessageBox.Show("Data has been saved");
}
}
}
For LOGOUT
public void logoutuser()
{
MySqlConnection cnn = new MySqlConnection(mysqlAddress);
MySqlCommand cmd;
cnn.Open();
try
{
cmd = cnn.CreateCommand();
cmd.CommandText = "update employee set logout = #logout WHERE IDNUMBER=#ID";
cmd.Parameters.AddWithValue("#logout", dateTimePicker1.Value);
cmd.Parameters.AddWithValue("#ID", id);
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (cnn.State == ConnectionState.Open)
{
cnn.Close();
MessageBox.Show("Data has been saved");
}
}
}

Check database if username exist in c# textbox

I am planning to check the username based on user input from the text box and I am planning to have the error message immediately after putting the existing username. for now i have this code. I am not experiencing errors but its not working. what am i missing here?
protected void btn_Registration_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertQuery = "insert into UserData(Username,Firstname,Lastname,Email,Password,CustomerType,DeliveryAddress,Zip,ContactNumber)values(#Username,#Firstname,#Lastname,#Email,#Password,#CustomerType,#DeliveryAddress,#Zip,#ContactNumber)";
SqlCommand scm = new SqlCommand(insertQuery, conn);
scm.Parameters.AddWithValue("#Username", txtUser.Text);
scm.Parameters.AddWithValue("#Firstname", txtFN.Text);
scm.Parameters.AddWithValue("#Lastname", txtLN.Text);
scm.Parameters.AddWithValue("#Email", txtEmail.Text);
scm.Parameters.AddWithValue("#Password", BusinessLayer.ShoppingCart.CreateSHAHash(txtPW.Text));
scm.Parameters.AddWithValue("#CustomerType", RadioButtonList1.SelectedItem.ToString());
scm.Parameters.AddWithValue("#DeliveryAddress", txtAddress.Text);
scm.Parameters.AddWithValue("#Zip", txtZip.Text);
scm.Parameters.AddWithValue("#ContactNumber", txtContact.Text);
scm.ExecuteNonQuery();
Session["Contact"] = txtContact.Text;
Session["Email"] = txtEmail.Text;
Session["DeliveryAddress"] = txtAddress.Text;
label_register_success.Text = ("Registration Successful!");
//Response.Redirect("Home.aspx");
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
protected void txtUser_TextChanged(object sender, EventArgs e)
{
if (Page.IsPostBack == true)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from UserDAta where Username='" + txtUser.Text + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
Imagemessage.Visible = true;
lblusercheck.Visible = true;
Imagemessage.ImageUrl = "NotAvailable.jpg";
lblusercheck.Text = "Username already exists.";
}
else
{
Imagemessage.Visible = true;
lblusercheck.Visible = true;
Imagemessage.ImageUrl = "Available.gif";
lblusercheck.Text = "You can choose this username.";
}
}
}
TextChange Event would not be called upon any single key press. What you should do is to use javascript to create a postback to the server (for example using __doPostBack) in the client side function keyup
Also, this would be a postback and you should not check for !isPostBack in the Handler.
Update:
Markup:
<asp:TextBox runat="server" ID="txt" onkeyup="check(this);" />
Javascript
function check(txt) {
__doPostBack('Control to Update', 'Filter--'+txt.value);
}
codebehind:
form_load:
parameter = Request["__EVENTARGUMENT"];
if (parameter != null && parameter.startsWith("Filter--"))
{
//Do your check here.
}
I don't like this kind of coding as it is messy.

How to display same format repeater for each row that has the same cell value

I have 50 different format repeaters. Each has to be bind according to the state.
I created a gridview with checkboxes. Whichever rows are checked to display those rows data in the corresponding repeater.
I am sending to the stored procedure multiple parameter and return a datatable. I loop through the datatable and on button click I get all repeaters except when the state is the same - it returns only the last one. I debug and the code runs through it but overwrites the previous row that had that state. How can I display all repeaters for the same state?
protected void GetVinData()
{
SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["DBConnection"]);
SqlCommand cmmd = new SqlCommand();
cmmd.CommandType = CommandType.StoredProcedure;
cmmd.CommandText = c
cmmd.Connection = cn;
cn.Open();
try
{
cmmd.Parameters.Add("#POLICY", SqlDbType.VarChar);
cmmd.Parameters["#POLICY"].Value = ddlPolicy.SelectedValue;
cmmd.Parameters.Add("#VIN", SqlDbType.VarChar);
cmmd.Parameters["#VIN"].Value = txtMsg.Value;
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(cmmd);
adapter.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["DBConnection"]);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetAllVinNumbers";
cmd.Connection = conn;
cmd.Parameters.Add("#POLICY", SqlDbType.VarChar);
cmd.Parameters["#POLICY"].Value = ddlPolicy.SelectedValue;
cmd.Parameters.Add("#VIN", SqlDbType.VarChar);
cmd.Parameters["#VIN"].Value = dr["VIN"].ToString();
if (dr["STATE"].ToString() == "AL")
{
try
{
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
Repeater_AL.DataSource = cmd.ExecuteReader();
Repeater_AL.DataBind();
Repeater_AL.Visible = true;
conn.Close();
conn.Dispose();
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
lblMessage.Visible = true;
}
finally
{
conn.Close();
conn.Dispose();
}
}
else if (dr["STATE"].ToString() == "AK")
{
try
{
if (conn.State != ConnectionState.Open)
conn.Open();
Repeater_AK.DataSource = cmd.ExecuteReader();
Repeater_AK.DataBind();
Repeater_AK.Visible = true;
conn.Close();
conn.Dispose();
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
lblMessage.Visible = true;
}
finally
{
conn.Close();
conn.Dispose();
}
}
else if (dr["STATE"].ToString() == "AZ")
{
try
{
if (conn.State != ConnectionState.Open)
conn.Open();
Repeater_AZ.DataSource = cmd.ExecuteReader();
Repeater_AZ.DataBind();
Repeater_AZ.Visible = true;
conn.Close();
conn.Dispose();
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
lblMessage.Visible = true;
}
finally
{
conn.Close();
conn.Dispose();
if (Repeater_AZ.Visible == true)
{
Repeater_AZ.Visible = true;
}
}
} ... and so on for 50 states
This slight refactoring may help:
protected void BindVin(string state)
{
Repeater rpt = null;
Control ctl = null;
string name = string.Empty;
SqlConnection conn = null;
SqlCommand cmd = null;
name = "Repeater_" + state;
ctl = Page.FindControl(name);
rpt = ctl as Repeater;
if (rpt != null) {
try {
conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings("DBConnection"));
cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetAllVinNumbers"; // should this have the state to get VINs for?
cmd.Connection = conn;
cmd.Parameters.Add("#POLICY", SqlDbType.VarChar);
cmd.Parameters("#POLICY").Value = ddlPolicy.SelectedValue;
cmd.Parameters.Add("#VIN", SqlDbType.VarChar);
cmd.Parameters("#VIN").Value = dr("VIN").ToString();
if (conn.State != ConnectionState.Open) {
conn.Open();
}
rpt.DataSource = cmd.ExecuteReader();
rpt.DataBind();
rpt.Visible = true;
conn.Close();
conn.Dispose();
} catch (Exception ex) {
lblMessage.Text = ex.Message;
lblMessage.Visible = true;
} finally {
conn.Close();
conn.Dispose();
}
}
}
protected void GetVinData()
{
SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["DBConnection"]);
SqlCommand cmmd = new SqlCommand();
cmmd.CommandType = CommandType.StoredProcedure;
cmmd.CommandText = c
cmmd.Connection = cn;
cn.Open();
try
{
cmmd.Parameters.Add("#POLICY", SqlDbType.VarChar);
cmmd.Parameters["#POLICY"].Value = ddlPolicy.SelectedValue;
cmmd.Parameters.Add("#VIN", SqlDbType.VarChar);
cmmd.Parameters["#VIN"].Value = txtMsg.Value;
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(cmmd);
adapter.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
BindVin(dr["STATE"].ToString());
}
}
}

How to set dateTimePickerValue to null or empty in c#

I have a windows form of controls combobox and datetimepicker..
I have given null or empty to combobox in page load..
so combobox shows empty intially while loading database values to it in windows form..
but the problem is
because of the datetimepicker is not kept to null or empty my form is showing message box as "the day is already existed" before form is desplaying..here my code follows
I want to show that message after combobox value is selected..
try
{
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection cn = new SqlConnection(connectionString);
cn.Open();
SqlCommand cmd = new SqlCommand("select employee_id,employee_name from Employee_Details", cn);
SqlDataReader dtr;
dtr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("employee_id", typeof(string));
dt.Columns.Add("employee_name", typeof(string));
dt.Load(dtr);
comboBox1.DisplayMember = "employee_id";
comboBox1.DisplayMember = "employee_name";
comboBox1.DataSource = dt;
comboBox1.SelectedItem = null;
if(comboBox1.SelectedItem == null)
{
txtemployeeid.Text = "";
txtemployeename.Text = "";
}
cn.Close();
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection cn = new SqlConnection(connectionString);
cn.Open();
try
{
SqlCommand cmd = new SqlCommand("select employee_id,Employee_name from Employee_Details where employee_name=('" + comboBox1.Text + "')", cn);
SqlDataReader dtr;
dtr = cmd.ExecuteReader();
if (dtr.Read())
{
string employee_id = (string)dtr["employee_id"];
string employee_name = (string)dtr["employee_name"];
txtemployeeid.Text = employee_id;
txtemployeename.Text = employee_name;
dtr.Close();
}
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
if (comboBox1.SelectedItem != null)
{
try
{
string dtp = dateTimePicker1.Value.ToString("dd/MM/yyyy");
SqlCommand cmd1 = new SqlCommand("select date from dailyattendance where date=('" + dtp + "') and employee_id='" + txtemployeeid.Text + "' and empployee_name='" + txtemployeename.Text + "' ", cn);
SqlDataReader dtr1;
dtr1 = cmd1.ExecuteReader();
if (dtr1.Read())
{
string date = (string)dtr1["date"];
if (dtp == date)
{
MessageBox.Show("this day is already existed");
}
}
dtr1.Close();
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
}
cn.Close();
}
can any one solve it please..Thanx in advance
You can simply use dtr.Text="";

Categories

Resources