Exits don't insert else insert - c#

I have started to learn asp.net. I am using VS 2013 Express for C#.
How to make that a some if case to check a duplicate value and if this value is exists then I get a red summary about it and can't insert to DB else insert to database and too with update button.
Can you help?
SqlConnection con = new SqlConnection(#"Data Source=TSS\SQLEXPRESS;Initial Catalog=DB;Integrated Security=True");
protected void Add(object sender, EventArgs e)
{
var vardas = GridView1.FooterRow.FindControl("txtname") as TextBox;
var pavarde = GridView1.FooterRow.FindControl("txtlastname") as TextBox;
var pozymis = GridView1.FooterRow.FindControl("DropDownList2") as DropDownList;
SqlCommand comm = new SqlCommand();
comm.CommandText = "insert into asmenys (name,lastname, status) values(#name,#lastname, #status)";
comm.Connection = con;
comm.Parameters.AddWithValue("#name", name.Text);
comm.Parameters.AddWithValue("#lastname", lastname.Text);
comm.Parameters.AddWithValue("#status", status![enter image description here][1].Text);
con.Open();
comm.ExecuteNonQuery();
con.Close();
DataBind();
}

When you say check if a value exists, what fields should not have duplicates? Those are the fields you have to write a select statement for to check if they exist first.
Example
protected void Add(object sender, EventArgs e)
{
var vardas = GridView1.FooterRow.FindControl("txtname") as TextBox;
var pavarde = GridView1.FooterRow.FindControl("txtlastname") as TextBox;
var pozymis = GridView1.FooterRow.FindControl("DropDownList2") as DropDownList;
SqlCommand comm = new SqlCommand();
comm.CommandText = "select lastname from asmenys where lastname = #lastname";
comm.Parameters.AddWithValue("#lastname", lastname.Text);
SqlDataReader reader = comm.ExecuteReader();
if (reader.HasRows)
{
Console.WriteLine("Values exist");
}
else
{
comm.CommandText = "insert into asmenys (name,lastname, status) values(#name,#lastname, #status)";
comm.Connection = con;
comm.Parameters.AddWithValue("#name", name.Text);
comm.Parameters.AddWithValue("#lastname", lastname.Text);
comm.Parameters.AddWithValue("#status", status![enter image description here][1].Text);
con.Open();
comm.ExecuteNonQuery();
con.Close();
DataBind();
}
}

Related

How to display fixed data on textbox based on cascading dropdown list in C#?

I would like to know how can I display fixed data, based on the cascading dropdown list the user chooses? For example, I have 3 dropdown lists, on the last dropdown list if the user chooses "Yes", textbox will display "Position is approved" and if the user chooses "No", textbox will display "Position not approved". This is my code. I don't know what else to, please help.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillPackage();
}
}
private void FillPackage()
{
string strConn = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT TopID, ToPackage FROM TableTop1";
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddl1.DataSource = objDs.Tables[0];
ddl1.DataTextField = "ToPackage";
ddl1.DataValueField = "TopID";
ddl1.DataBind();
ddl1.Items.Insert(0, "--Select--");
}
else
{
lblMsg.Text = "No Package found";
}
}
private void FillPurpose(int TopID)
{
string strConn = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT PurposeID, Purpose FROM TablePurpose1 WHERE TopID =#TopID";
cmd.Parameters.AddWithValue("#TopID", TopID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddl2.DataSource = objDs.Tables[0];
ddl2.DataTextField = "Purpose";
ddl2.DataValueField = "PurposeID";
ddl2.DataBind();
ddl2.Items.Insert(0, "--Select--");
}
else
{
lblMsg.Text = "Please consult with focal person";
}
}
private void FillReason(int PurposeID)
{
string strConn = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT ReasonID, Reason FROM TableReason1 WHERE PurposeID =#PurposeID";
cmd.Parameters.AddWithValue("#PurposeID", PurposeID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddl3.DataSource = objDs.Tables[0];
ddl3.DataTextField = "Reason";
ddl3.DataValueField = "ReasonID";
ddl3.DataBind();
ddl3.Items.Insert(0, "--Select--");
}
else
{
lblMsg.Text = "Please consult with focal person";
}
}
Since you have a Page_Load method in your snippet I'll consider your are using asp.net web forms. If that is the case you just have to handle the event emitted by the DropDownList component when it is changed.
I'm your c# code you should create a method to handle the event of an item being selected in your DropDownList, something like this:
protected void ItemSelected(object sender, EventArgs e)
{
if (ddl3.SelectedItem.Value == "Yes")
{
// Change text box text
}
}
And then you just have to hook your event handler to the component:
<asp:DropDownList ID="ddl3" runat="server" AutoPostBack="True"
onselectedindexchanged="ItemSelected">
</asp:DropDownList>

Get ID of selected value in drop down

I am trying to save data in my database, as part of that I am trying to get the ID (primary key) of my selected item in my drop down.
It keeps saving the same ID all the time. It only saves the first ID of any chosen item. How can I adjust my code so that it saves the different IDs based on what I have chosen in my drop down
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(
WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("Select UserRoleID, RoleType from tb_UserRoles", con);
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "RoleType";
DropDownList1.DataValueField = "UserRoleID";
DropDownList1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(
WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("sp_UserInsertUpdate", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
String ID = DropDownList1.SelectedValue;
cmd.Parameters.AddWithValue("UserID", (hfUserID.Value == "" ? 0 : Convert.ToInt32(hfUserID.Value)));
cmd.Parameters.AddWithValue("UserRoleID", ID);
cmd.Parameters.AddWithValue("Username", TextBox1.Text);
cmd.Parameters.AddWithValue("Password", TextBox2.Text);
cmd.Parameters.AddWithValue("Email", TextBox3.Text);
cmd.Parameters.AddWithValue("DateCreate", TextBox4.Text);
cmd.ExecuteNonQuery();
con.Close();
}
This is because every time you click on button. click event is occurred but before that it executes the Page Load event and In page load event you have added the logic of binding drop down. it means whenever you click button then every time it first load the drop down list then comes to the click event. for this purpose you just need to add one if condition using IsPostBack.
Make the changes as below
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack) //Added
{
SqlConnection con = new SqlConnection(
WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("Select UserRoleID, RoleType from tb_UserRoles", con);
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "RoleType";
DropDownList1.DataValueField = "UserRoleID";
DropDownList1.DataBind();
}
}
You should check !IsPostBack
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack) // Add this If condition
{
SqlConnection con = new SqlConnection(
WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("Select UserRoleID, RoleType from tb_UserRoles", con);
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "RoleType";
DropDownList1.DataValueField = "UserRoleID";
DropDownList1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(
WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("sp_UserInsertUpdate", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
String ID = DropDownList1.SelectedValue;
cmd.Parameters.AddWithValue("UserID", (hfUserID.Value == "" ? 0 : Convert.ToInt32(hfUserID.Value)));
cmd.Parameters.AddWithValue("UserRoleID", ID);
cmd.Parameters.AddWithValue("Username", TextBox1.Text);
cmd.Parameters.AddWithValue("Password", TextBox2.Text);
cmd.Parameters.AddWithValue("Email", TextBox3.Text);
cmd.Parameters.AddWithValue("DateCreate", TextBox4.Text);
cmd.ExecuteNonQuery();
con.Close();
}

Cannot set the SelectedValue in a ListControl with an empty ValueMember in winform using c#

I have a combobox that loads data from database but i got an error that you cannot set the selectedValue in a ListControl Although i have set the selectValue to a Primary key of a Table. But still getting error on runtime.. Here is the Code..
private void FormAddStudent_Load(object sender, EventArgs e)
{
//For combobox Campuse
cBoxCampus.DataSource = GetAllCampuses();
cBoxCampus.DisplayMember = "campus_name";
cBoxCampus.SelectedValue = "campus_id";
//Foe ComboBox Department
cBoxDepartment.DataSource = GetAllDepartment();
cBoxDepartment.DisplayMember = "depname";
cBoxDepartment.SelectedValue = "depid";
}
and this is the code behind Insert Button
private void btnInsert_Click(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["UMSdbConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT ISNULL(MAX(std_id),0)+1 FROM Student", con);
cmd.CommandType = CommandType.Text;
tbID.Text = cmd.ExecuteScalar().ToString();
{
using (SqlCommand cmd1 = new SqlCommand("INSERT INTO Student (std_id,std_name,std_f_name,std_mob,std_gender,std_cnic,std_campus,std_dep,std_address,std_batch,std_batch_year)VALUES(#std_id,#std_name,#std_f_name,#std_mob,#std_gender,#std_cnic,#std_campus,#std_dep,#std_address,#std_batch,#std_batch_year)VALUES(#campus_id,#campus_name)", con))
{
cmd1.CommandType = CommandType.Text;
cmd1.Parameters.AddWithValue("#std_id", tbID.Text);
cmd1.Parameters.AddWithValue("#std_name", tbName.Text);
cmd1.Parameters.AddWithValue("#std_f_name", tbFatherName.Text);
cmd1.Parameters.AddWithValue("#std_mob", tbMobNumber.Text);
cmd1.Parameters.AddWithValue("#std_gender", GetGender());
cmd1.Parameters.AddWithValue("#std_cnic", tbMobNumber.Text);
cmd1.Parameters.AddWithValue("#std_campus",(cBoxCampus.SelectedIndex == -1) ? 0: cBoxCampus.SelectedValue);
cmd1.Parameters.AddWithValue("#std_dep", (cBoxDepartment.SelectedIndex == -1) ? 0 : cBoxDepartment.SelectedValue);
cmd1.Parameters.AddWithValue("#std_address", tbAddress.Text);
cmd1.Parameters.AddWithValue("#std_batch", tbBatchNo.Text);
cmd1.Parameters.AddWithValue("#std_batch_year", tbBatchYear.Text);
cmd1.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Saved");
}
}
}
}
Replace
cBoxCampus.SelectedValue = "campus_id";
With ListControl.ValueMember Property
cBoxCampus.ValueMember = "campus_id";
Do similar operation for cBoxDepartment

Why does this UPDATE command not update the data, even though there is no error?

I have a users table having fields uname, ushortname and pswd as well ucode as primary key.
The following UPDATE is not working:
protected void Page_Load(object sender, EventArgs e)
{
string uname = Request.QueryString["uname"];
string ucode = Request.QueryString["ucode"];
if (!string.IsNullOrEmpty(uname))
{
SqlCommand cmd = new SqlCommand("select * from users WHERE ucode=#ucode", conn);
SqlDataAdapter dadapter = new SqlDataAdapter();
conn.Open();
txtUserName.ReadOnly = false;
txtUserShortName.ReadOnly = false;
txtPassword.ReadOnly = false;
dadapter.SelectCommand = cmd;
cmd.Parameters.Add(new SqlParameter("#ucode", ucode));
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
LblUcode.Text = dr["ucode"].ToString();
txtPassword.Text=dr["pswd"].ToString();
txtUserShortName.Text = dr["ushortname"].ToString();
txtUserName.Text = dr["uname"].ToString();
}
dr.Close();
conn.Close();
}
}
SqlCommand cmd = new SqlCommand("update users Set uname=#Uname,ushortname=#Ushortname,pswd=HASHBYTES('MD5',#Pswd) where ucode=#UCODE", conn);
cmd.Parameters.AddWithValue("#Uname", txtUserName.Text);
cmd.Parameters.AddWithValue("#Ushortname", txtUserShortName.Text);
cmd.Parameters.AddWithValue("#Pswd", txtPassword.Text);
cmd.Parameters.AddWithValue("#UCODE", LblUcode.Text);
cmd.ExecuteNonQuery();
cmd.Dispose();
There is no error, the data simply isn't being updated.
You need to make sure the parameter names match exactly what they do in your sql string.
cmd.Parameters.AddWithValue("#UCODE", UCODE);
Also, either wrap all of that in a using or try/finally to dispose of the connection. I'm assuming you've already got code to open the connection before trying to execute it.
Try this:-
using(SqlConnection conn = new SqlConnection(CS))
{
using (SqlCommand cmd = new SqlCommand("update users Set uname=#Uname,ushortname=#Ushortname,pswd=HASHBYTES('MD5',#Pswd) where ucode=#UCODE ", conn))
{
cmd.Parameters.AddWithValue("#Uname", txtUserName.Text);
cmd.Parameters.AddWithValue("#Ushortname", txtUserShortName.Text);
cmd.Parameters.AddWithValue("#Pswd", txtPassword.Text);
cmd.Parameters.AddWithValue("#UCODE", UCODE);
conn.Open();
cmd.ExecuteNonQuery();
}
}
You are missing # in Ucode. Also, its a good practice to wrap your code inside using block check this.
See the edited below code:-
if (!PostBack)
{
string databaseconnectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString;
string sql = "update users Set uname=#Uname,ushortname=#Ushortname,pswd=HASHBYTES('MD5',#Pswd) where ucode=#UCODE";
using (SqlConnection conn = new SqlConnection(databaseconnectionstring))
{
conn.Open();
using (SqlCommand cmd= new SqlCommand())
{
cmd.CommandText=sql;
cmd.Connection=databaseconnectionstring;
cmd.Parameters.AddWithValue("#Uname",txtUserName.Text );
cmd.Parameters.AddWithValue("#Ushortname",txtUserShortName.Text );
cmd.Parameters.AddWithValue("#Pswd",txtPassword.Text );
cmd.Parameters.AddWithValue("#UCODE", UCODE);
cmd.ExecuteNonQuery();
conn.Close();
cmd.Dispose();
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
string bsname = Request.QueryString["bsname"];
string bscode = Request.QueryString["bscode"];
if (!string.IsNullOrEmpty(bsname))
{
if (string.IsNullOrEmpty(txtBsName.Text))
{
SqlCommand cmd = new SqlCommand("select * from bs WHERE bscode=#bscode", conn);
SqlDataAdapter dadapter = new SqlDataAdapter();
conn.Open();
txtBsName.ReadOnly = false;
dadapter.SelectCommand = cmd;
cmd.Parameters.Add(new SqlParameter("#bscode", bscode));
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
lblBsCode.Text = dr["bscode"].ToString();
txtBsName.Text = dr["bsname"].ToString();
}
dr.Close();
conn.Close();
}
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
conn.Open();
string UCODE = LblUcode.Text;
SqlCommand cmd = new SqlCommand("update users Set uname=#Uname,ushortname=#Ushortname,pswd=HASHBYTES('MD5',#Pswd) where ucode=#UCODE", conn);
cmd.Parameters.AddWithValue("#Uname",txtUserName.Text );
cmd.Parameters.AddWithValue("#Ushortname",txtUserShortName.Text );
cmd.Parameters.AddWithValue("#Pswd",txtPassword.Text );
cmd.Parameters.AddWithValue("#UCODE", UCODE);
cmd.ExecuteNonQuery();
cmd.Dispose();
ShowMessage("Company Data update Successfully......!");
clear();
}
Thank you all its working now with the help of above code.

Adding just Unique Data to Gridview

I have a table like this. Columns --> (MUSTERI, AVUKAT, HESAP (Unique))
My page design like this.
Simply, first dropdown is MUSTERI, second dropdown is AVUKAT, when i click EKLE (it means ADD) button, automaticyly getting HESAP (unique) and showing on gridview.
What i want is, if any user try to add a data which they are the same HESAP, geting an error.
For example;There is a data "2M LOJİSTİJ" "ALİ ORAL" "889" in my gridview.
Someone try to add a data like "2M LOJİSTİK" "EMRA SARINÇ" "889" showing an error and don't add to table.
My Add_Click button code is
protected void Add_Click(object sender, EventArgs e)
{
string strConnectionString = ConfigurationManager.ConnectionStrings["SqlServerCstr"].ConnectionString;
SqlConnection myConnection = new SqlConnection(strConnectionString);
myConnection.Open();
string hesap = Label1.Text;
string musteriadi = DropDownList1.SelectedItem.Value;
string avukat = DropDownList2.SelectedItem.Value;
SqlCommand cmd = new SqlCommand("INSERT INTO AVUKAT VALUES (#MUSTERI, #AVUKAT, #HESAP)", myConnection);
cmd.Parameters.AddWithValue("#HESAP", hesap);
cmd.Parameters.AddWithValue("#MUSTERI", musteriadi);
cmd.Parameters.AddWithValue("#AVUKAT", avukat);
cmd.Connection = myConnection;
SqlDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
Response.Redirect(Request.Url.ToString());
myConnection.Close();
}
And my first dropdown MUSTERI (getting HESAP auto by this field)
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string strConnectionString = ConfigurationManager.ConnectionStrings["SqlServerCstr"].ConnectionString;
SqlConnection myConnection = new SqlConnection(strConnectionString);
myConnection.Open();
string hesapNo = DropDownList1.SelectedItem.Value;
string query = "select A.HESAP_NO from YAZ..MARDATA.S_TEKLIF A where A.MUS_K_ISIM = '" + hesapNo + "'";
SqlCommand cmd = new SqlCommand(query, myConnection);
if (DropDownList1.SelectedValue != "0")
{
Add.Enabled = true;
Label1.Text = cmd.ExecuteScalar().ToString();
}
else
{
Add.Enabled = false;
}
Label1.Visible = false;
myConnection.Close();
}
How can i blocking insert data which already have the same HESAP?
first check HESAP is exist or not in #AVUKAT then insert new entry.
protected void Add_Click(object sender, EventArgs e)
{
string strConnectionString = ConfigurationManager.ConnectionStrings["SqlServerCstr"].ConnectionString;
SqlConnection myConnection = new SqlConnection(strConnectionString);
myConnection.Open();
string hesap = Label1.Text.Trim();
string musteriadi = DropDownList1.SelectedItem.Value;
string avukat = DropDownList2.SelectedItem.Value;
string strsql= "SELECT * FROM AVUKAT WHERE HESAP = " + hesap;
SqlCommand com = new SqlCommand(strsql, myConnection);
SqlDataReader dread = com.ExecuteReader();
dread.read();
if(dread.HasRows)
{
myConnection.Close();
return;
}
SqlCommand cmd = new SqlCommand("INSERT INTO AVUKAT VALUES (#MUSTERI, #AVUKAT, #HESAP)", myConnection);
cmd.Parameters.AddWithValue("#HESAP", hesap);
cmd.Parameters.AddWithValue("#MUSTERI", musteriadi);
cmd.Parameters.AddWithValue("#AVUKAT", avukat);
cmd.Connection = myConnection;
SqlDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
Response.Redirect(Request.Url.ToString());
myConnection.Close();
}

Categories

Resources