Get ID of selected value in drop down - c#

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();
}

Related

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

Unable to post data in drop down list from DB

I am new in writing code. Getting following error when trying to post data in drop down list from DB.
My Objective is: Post data in Drop Down List from DB.
Error message: Process can't access the file because it is being used
by another process
using System.Data;
using System.Configuration;
public partial class Default : System.Web.UI.Page
{
//SqlCommand cmd;
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;Database=Database1;AttachDbFilename=C:\Database1.mdf;Integrated Security=True;User Instance=True");
protected void Page_Load(object sender, EventArgs e)
{
Populate1();
}
protected void Button1_Click1(object sender, EventArgs e)
{
/* SqlCommand cmd = new SqlCommand("insert into service_type (type) values(' " + TextBox1.Text + " ')",
new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
cmd.Connection.Open();
cmd.Connection.Close();
cmd.Connection.Dispose(); */
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into service_type (type) values(' " + TextBox1.Text + " ')";
cmd.ExecuteNonQuery();
con.Close();
}
public void Populate1()
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM [serice_type]", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
cmd.Connection.Open();
SqlDataReader ddlValues;
ddlValues = cmd.ExecuteReader();
DropDownList1.DataSource = ddlValues;
DropDownList1.DataValueField = "theType";
DropDownList1.DataTextField = "theType";
DropDownList1.DataBind();
cmd.Connection.Close();
cmd.Connection.Dispose();
}
}

Asp Dropdownlist does not return selected value. (Dropdownlist is Databound)

I have created a dropdownlist, which loads its data from a table column. Now I want to select the value of dropdownlist on Index_change_event.
protected void Page_Load(object sender, EventArgs e)
{
string username = Session["username"].ToString();
SqlConnection con = new SqlConnection("Data Source=DLINK\\SQLEXPRESS;User ID=sa;Password=logmein;Initial Catalog=AndroidAppDB");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
string query = "select Fence_Name from Fence where Username='" + username + "'";
SqlCommand command = new SqlCommand(query, con);
DropDownList1.DataSource = command.ExecuteReader();
DropDownList1.DataValueField = "Fence_Name";
DropDownList1.DataTextField = "Fence_Name";
DropDownList1.DataBind();
con.Close();
//arr = Session["arr"].ToString();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (!IsPostBack)
{
Label2.Text = DropDownList1.SelectedItem.Value;
}
}
Remove if (!IsPostBack) from DropDownList1_SelectedIndexChanged event and if (!IsPostBack) should be on Page_Load event.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Label2.Text = DropDownList1.SelectedItem.Value;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string username = Session["username"].ToString();
SqlConnection con = new SqlConnection("Data Source=DLINK\\SQLEXPRESS;User ID=sa;Password=logmein;Initial Catalog=AndroidAppDB");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
string query = "select Fence_Name from Fence where Username='" + username + "'";
SqlCommand command = new SqlCommand(query, con);
DropDownList1.DataSource = command.ExecuteReader();
DropDownList1.DataValueField = "Fence_Name";
DropDownList1.DataTextField = "Fence_Name";
DropDownList1.DataBind();
con.Close();
}
}
You are only checking !IsPostBack. As the event is firing from a postback this will never be run. Also, be careful that you are not re-binding the datasource and therefore changing the selected value on page_load.

Exits don't insert else insert

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();
}
}

DropDownList Value won't change

When I select any value from the DropDownList, the first one gets selected.
The code's purpose is whenever I choose a value from the DropDownList the corresponding value from the database should be displayed in the TextBox.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("connection string");
con.Open();
DataTable Seminars = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT SeminarName, ID FROM SeminarData", con);
adapter.Fill(Seminars);
DropDownList1.DataSource = Seminars;
DropDownList1.DataTextField = "SeminarName";
DropDownList1.DataValueField = "SeminarName";
DropDownList1.DataBind();
con.Close();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("connection string");
con.Open();
DataTable dt = new DataTable();
SqlCommand sqlCmd = new SqlCommand("SELECT SeminarNameE,TrainerName FROM SeminarData WHERE SeminarName='" + DropDownList1.SelectedItem.Value +"'", con);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
TextBox1.Text = dt.Rows[0]["SeminarNameE"].ToString();
TextBox2.Text = dt.Rows[0]["TrainerName"].ToString();
}
}
Replace your page load with this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) {
SqlConnection con = new SqlConnection("connection string");
con.Open();
DataTable Seminars = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT SeminarName, ID FROM SeminarData", con);
adapter.Fill(Seminars);
DropDownList1.DataSource = Seminars;
DropDownList1.DataTextField = "SeminarName";
DropDownList1.DataValueField = "SeminarName";
DropDownList1.DataBind();
con.Close();
}
}
It needs !Page.IsPostBack, because everytime you bind, you clear any selections. In this code, it binds on every page load. Adding !Page.IsPostback will ensure it binds only the first load.

Categories

Resources