In page load I'm loading a drop down list with names from a postgreSQL database, using SQL.
Later in the code I want to save the selected value in the drop down list into a string variable.
That won't happen. What happens is the first value in the list (index 0) always saves, no matter of which I have selected.
Heres is page load (works fine):
protected void Page_Load(object sender, EventArgs e)
{
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;Database=SYS;User Id=postgres;Password=postgres;");
conn.Open();
NpgsqlCommand command = new NpgsqlCommand("SELECT name FROM tbl_syv ORDER BY name", conn);
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
ddPersons.Items.Add((string)dr["name"] + " " + " ");
}
}
Here is Button1_Click. I want to save the selected value into string variable syv.
protected void Button1_Click(object sender, EventArgs e)
{
string syv = ddPersons.SelectedItem.Text;
string name = txtName.Text;
int studentid = 0;
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;Database=sSYS;User Id=postgres;Password=postgres;");
conn.Open();
string sql = "SELECT id FROM tbl_student WHERE name = '" + name + "'";
NpgsqlCommand command = new NpgsqlCommand(sql, conn);
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
studentid = (int)dr["id"];
}
}
I have tried
string syv = ddPersons.SelectedItem.Text;
string syv = ddPersons.SelectedItem.Value;
string syv = ddPersons.Text;
string syv = ddPersons.SelectedValue;
It might be that ViewState is saving the state of your page. Why don't you include the following line in your Page_Load method:
if ( !IsPostBack)
{
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;Database=SYS;User Id=postgres;Password=postgres;");
conn.Open();
NpgsqlCommand command = new NpgsqlCommand("SELECT name FROM tbl_syv ORDER BY name", conn);
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
ddPersons.Items.Add((string)dr["name"] + " " + " ");
}
}
It will prevent the Page_Load to populate duplicate items every time someone clicks on the button and prevents the ViewState to interfere with the state of your controls.
Related
I am trying to Display a name in the textbox from the database if the ID entered by the user matches the record in the MS ACCESS DATABASE.
I'm getting the error Data type mismatch in criteria expression at the line int count = Convert.ToInt32(cmd.ExecuteScalar());
The following is my aspx.cs code-
protected void Button1_Click(object sender, EventArgs e)
{
clear();
idcheck();
DataTable dt = new DataTable();
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\dfg\fd\Visual Studio 2010\WebSites\WebSite21\App_Data\UPHealth.mdb");
con.Open();
str = "SELECT [DoctorName] FROM [DoctorInfo] WHERE DoctorID='" + TextBox1.Text.Trim() + "'";
OleDbCommand cmd = new OleDbCommand(str, con);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
TextBox2.Text = dr["DoctorID"].ToString();
dr.Close();
con.Close();
}
}
public void idcheck()
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\dfg\fd\Visual Studio 2010\WebSites\WebSite21\App_Data\UPHealth.mdb");
con.Open();
str = "SELECT count(DoctorName) FROM [DoctorInfo] WHERE DoctorID='" + TextBox1.Text.Trim() + "'";
OleDbCommand cmd = new OleDbCommand(str, con);
int count = Convert.ToInt32(cmd.ExecuteScalar());
if (count > 0)
{
Label21.Text = "Doctor Name";
}
else
{
Label21.Text = "Id Does not Exist";
}
}
void clear()
{
TextBox2.Text = "";
}
I guess that is because you as passing in an ID, which is usually a numeric value, as a text field:
DoctorID='" + TextBox1.Text.Trim() + "'
Which should be:
DoctorID=" + TextBox1.Text.Trim()
Another problem arises, since you are vulnerable to SQL injection. What if the text box contained 1; delete users? Then your entire users table would be empty. The lesson learned: use parameterized queries!
Then you can express the SQL as:
DoctorID= ?
And add the parameter to the request:
cmd.Parameters.AddWithValue("?", TextBox1.Text.Trim());
I have a form that should edit the information in the database. First, I query the database using an URL parameter to get the record and display them in textboxes so I could update them. That part of the code works the issue is when I press submit to update the data after changing what's on the textboxes. Only LastMod column gets updated. I think the page_load fires twice and overwrites what's on the textboxes before the button click event fires.
Here's the code.
public partial class Edit : System.Web.UI.Page
{
int aID;
SqlConnection conn = new SqlConnection(#connectionstring);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
conn.Open();
aID = Convert.ToInt16(Request.QueryString["ID"]);
string sql = "select * from Contacts where ID = '" + aID + "' ";
SqlDataAdapter adap = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
adap.Fill(ds);
txtFName.Text = ds.Tables[0].Rows[0]["Fname"].ToString();
txtLName.Text = ds.Tables[0].Rows[0]["Lname"].ToString();
txtEmail.Text = ds.Tables[0].Rows[0]["EmailAdd"].ToString();
lblLastMod.Text = ds.Tables[0].Rows[0]["LastMod"].ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
DateTime date = DateTime.Now;
SqlCommand sqlComm = new SqlCommand();
sqlComm = conn.CreateCommand();
sqlComm.CommandText = #"UPDATE Contacts SET Fname=#FName, Lname = #LName, EmailAdd = #Eadd,LastMod = #LMod WHERE ID=#ID";
sqlComm.Parameters.Add("#FName", SqlDbType.NChar);
sqlComm.Parameters["#FName"].Value = txtFName.Text.Trim();
sqlComm.Parameters.Add("#LName", SqlDbType.NChar);
sqlComm.Parameters["#LName"].Value = txtLName.Text.Trim();
sqlComm.Parameters.Add("#Eadd", SqlDbType.NChar);
sqlComm.Parameters["#Eadd"].Value = txtEmail.Text.Trim();
sqlComm.Parameters.Add("#LMod", SqlDbType.DateTime);
sqlComm.Parameters["#LMod"].Value = date;
sqlComm.Parameters.Add("#ID", SqlDbType.Int);
sqlComm.Parameters["#ID"].Value = aID;
conn.Open();
sqlComm.ExecuteNonQuery();
conn.Close();
}
}
I tried adding !IsPostback in my Page_Load method but nothing gets updated even the LastMod record.
Thanks for any help I get.
You declare a variable, aID, at the top of the page, and you set a value in it in the page load. You then also use it in the click, but you never re-set it. Therefore, for postback, it will not have a value. Move this to page load above your "if not ispostback"
protected void Page_Load(object sender, EventArgs e)
{
aID = Convert.ToInt16(Request.QueryString["ID"]);
if (!IsPostBack)
{
conn.Open();
string sql = "select * from Contacts where ID = '" + aID + "' ";
Asp.net code :
Select Employee : </b>
<asp:DropDownList ID="DropDownListSelectEmployee" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="DropDownListSelectEmployee_SelectedIndexChanged"
OnTextChanged="DropDownListSelectEmployee_TextChanged" >
</asp:DropDownList>
Code behind :
public void DropDownListSelectEmployee_Fill()
{
DropDownListSelectEmployee.Items.Clear();
string q = "select username from nworksuser where _type='Employee' or _type='Admin_Employee';";
MySqlCommand cmd = new MySqlCommand(q, conn);
conn.Open();
string user = "";
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
user = rdr.GetString("username");
DropDownListSelectEmployee.Items.Add(user);
}
conn.Close();
}
protected void DropDownListSelectEmployee_TextChanged(object sender, EventArgs e)
{
string q = "select uid,fname,mname,lname,date_format(hire_date,'%Y-%m-%d'),desg,date_format(dob,'%Y-%m-%d'),AddressLine1,AddressLine2,state,city,pincode,country,MobileNo,UserActive,username,date_format(annivarsary,'%Y-%m-%d'),email from nWorksUser where Username='" + DropDownListSelectEmployee.Text + "'";
MySqlCommand cmd = new MySqlCommand(q, conn);
conn.Open();
MySqlDataAdapter dataAdapter = new MySqlDataAdapter(q, conn);
DataTable dt = new DataTable();
dataAdapter.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
txtFirstName.Text = dr[1].ToString();
txtMiddleName.Text = dr[2].ToString();
txtLastName.Text = dr[3].ToString();
txtMobile.Text = dr[13].ToString();
txtUsername.Text = dr[15].ToString();
txtState.Text = dr[9].ToString();
txtPincode.Text = dr[11].ToString();
txtEmail.Text = dr[17].ToString();
txtDob.Text = dr[6].ToString();
txtDesignation.Text = dr[5].ToString();
txtDateofHire.Text = dr[4].ToString();
txtDateofAnnivarsary.Text = dr[16].ToString();
txtCountry.Text = dr[12].ToString();
txtCity.Text = dr[10].ToString();
txtAddressLine2.Text = dr[7].ToString();
txtAddressLine1.Text = dr[8].ToString();
if (dr[14].ToString().Length == 4)
{
RdoGender.SelectedIndex = 1;
}
else
{
RdoGender.SelectedIndex = 2;
}
conn.Close();
}
}
protected void DropDownListSelectEmployee_SelectedIndexChanged(object sender, EventArgs e)
{
}
Drop down list contains users name from database. Now I want that, as you select any user from drop down list it should show his details in form and its working. But problem is that after choosing any one user, that name appears in drop down for moment and reset it to the first name of drop down list any showing details of its related instead of selected. Its not accepting any other name except first name drop down list. I am not getting where is the problem. Please help me.
You need to wrap the code in DropDownListSelectEmployee_Fill with if (!Page.IsPostBack). On a post back the drop down contents will be repopulating, causing its state to reset, which is why you're seeing the "unexpected behaviour".
Checking for post backs, you can make certain the drop down isn't affected on a selection change:
public void DropDownListSelectEmployee_Fill()
{
if (!Page.IsPostBack)
{
DropDownListSelectEmployee.Items.Clear();
string q = "select username from nworksuser where _type='Employee' or _type='Admin_Employee';";
MySqlCommand cmd = new MySqlCommand(q, conn);
conn.Open();
string user = "";
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
user = rdr.GetString("username");
DropDownListSelectEmployee.Items.Add(user);
}
conn.Close();
}
}
When I use the following code the loop is iterating twice and I am getting error message as "The variable name '#projectName1' has already been declared. Variable names must be unique within a query batch or stored procedure." and resetting all the values of the table in the datagridview as well as in the table. Actually I want to update the DataGridView in the form itself by selecting the cell and it should reflect the same in the database too.
private void btnUpdate_Click(object sender, EventArgs e)
{
SqlConnection con = Helper.getconnection();
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
string myCmd = string.Empty;
foreach (DataGridViewRow myDgrow in dataGridView2.Rows)
{
myCmd = "Update Details set ProjectName='" + myDgrow.Cells["ProjectName"].Value + "', Description = '" + myDgrow.Cells["Description"].Value + "', DateStarted='" + myDgrow.Cells["DateStarted"].Value + "',TeamSize='" + myDgrow.Cells["TeamSize"].Value + "',Manager='" + myDgrow.Cells["Manager"].Value + "'";
cmd.Parameters.AddWithValue("#projectName1", myDgrow.Cells["ProjectName"].Value);
cmd.Parameters.AddWithValue("#Description1", myDgrow.Cells["Description"].Value);
cmd.Parameters.AddWithValue("#DateStarted1", myDgrow.Cells["DateStarted"].Value);
cmd.Parameters.AddWithValue("#TeamSize1", myDgrow.Cells["TeamSize"].Value);
cmd.Parameters.AddWithValue("#Manager1", myDgrow.Cells["Manager"].Value);
cmd.CommandText = myCmd;
cmd.ExecuteNonQuery();
dataGridView2.Update();
myCmd = string.Empty;
}
DataTable details = new DataTable();
SqlDataAdapter da = new SqlDataAdapter();
try
{
da.Update(details);
}
catch (Exception exceptionObj)
{
MessageBox.Show(exceptionObj.Message.ToString());
}
}
You are using foreach loop and adding the parameters each time to the same command. Either clear the parameters each time you iterate in the loop or create a new command each time..
I am making a list of records in a web form with edit and delete options. I have retrieved the values in the text box fields for update. Now, when
the user clicks the update button, the record is updated.
How can I do it remaining on the same page or redirected to another page?
This is my code:
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
binddata();
}
}
SqlConnection con;
SqlDataAdapter da;
DataSet ds;
void binddata()
{
string pid = Request.QueryString["Prod_Id"];
con = new SqlConnection("Data Source=.\\sqlexpress; initial catalog=PracticeDb; user id=sa; pwd=manager;");
con.Open();
da = new SqlDataAdapter("Select * from Products where Prod_Id='" + pid + "'", con);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
string P_Name = ds.Tables[0].Rows[0]["Prod_Name"].ToString();
string U_Prce = ds.Tables[0].Rows[0]["Unit_Price"].ToString();
string I_Hnd = ds.Tables[0].Rows[0]["In_Hand"].ToString();
string Fxd = ds.Tables[0].Rows[0]["Fixed"].ToString();
string Stus = ds.Tables[0].Rows[0]["Status"].ToString();
TextBox1.Text = P_Name;
TextBox2.Text = U_Prce;
TextBox3.Text = I_Hnd;
TextBox4.Text = Fxd;
TextBox5.Text = Stus;
}
protected void Unnamed1_Click(object sender, EventArgs e)
{
string pid = Request.QueryString["Prod_Id"];
var Pd_nme = TextBox1.Text;
decimal Uni_prce = decimal.Parse(TextBox2.Text);
int In_hnd = int.Parse(TextBox3.Text);
string Fxd = TextBox4.Text;
string Stus = TextBox5.Text;
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=.\\sqlexpress; initial catalog=PracticeDb; user id=sa; pwd=manager;");
con.Open();
string qry = "UPDATE PRODUCTS SET Prod_Name='" + Pd_nme + "',Unit_Price='" + Uni_prce + "',In_Hand='" + In_hnd + "',Fixed='" + Fxd + "',Status='" + Stus + "' where Prod_Id='" + pid + "'";
SqlCommand cmd = new SqlCommand(qry, con);
cmd.ExecuteNonQuery();
con.Close();
}
}
}
Thanks.
You are trying to access the query string on a postback, which does not make any sense...now you have multiple options to achieve what you are trying to do here...i will try to list one or two of them....
Hidden Field:
Create a hidden field in the page using:
<asp:HiddenField runat="server" ID="hdn_field" />
and in your page_load set its value to a Prod_Id from a QueryString...and now you can access it in your postbacks by just hdnField.Value..
ViewState:
You can save the value in a ViewState and use it in your postbacks....
AJAX:
Create an ajax call to a same or different page and send the object to the server by serializing it to JSON/XML and then handle the update from that page