How to get value from database to a label? - c#

I have a table from a database, i want display a value from table to my label1. This is my code:
string query="Data Source=Bun; user Id=sa; Password=sa; Initial Catalog=eBilling;";
SqlConnection con = new SqlConnection(query);
con.Open();
string query1 = "select prodName from ProductMaster where #name='Bar Counter' ";
SqlCommand cmd = new SqlCommand(query1, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()) {
label1.Text = dr.GetValue(1).ToString();
textBox1.Text = dr.GetValue(0).ToString();
}
but after that, i must click on this label to display the value. What can i do with this code to display my value in label while don't need click to anything?

As #wqrahd said
protected void Page_Load(object sender, EventArgs e)
{
string query="Data Source=Bun; user Id=sa; Password=sa; Initial Catalog=eBilling;";
SqlConnection con = new SqlConnection(query);
con.Open();
string query1 = "select prodName from ProductMaster where #name='Bar Counter' ";
SqlCommand cmd = new SqlCommand(query1, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()) {
label1.Text = dr.GetValue(1).ToString();
textBox1.Text = dr.GetValue(0).ToString();
}

place this code in page_load method of your WinForm.

Write a different function with your code and call it in page_load events and other events if required:
protected void Page_Load(object sender, EventArgs e)
{
setLableText();
}
private void setLableText()
{
string query="Data Source=Bun; user Id=sa; Password=sa; Initial Catalog=eBilling;";
SqlConnection con = new SqlConnection(query);
con.Open();
string query1 = "select prodName from ProductMaster where #name='Bar Counter' ";
SqlCommand cmd = new SqlCommand(query1, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()) {
label1.Text = dr.GetValue(1).ToString();
textBox1.Text = dr.GetValue(0).ToString();
}
}

If this is for the web application:
In order to show the label as soon as user opens the page.
You must write the code in page load.
Also If you want to display this Label only the first time and after that value changes over some event, then place the code as:
..Page_Load(..)
{
(!IsPostBack)
{
}
}
So that Label shows value first time page loads.
Any doubt you can ask again. :)
For window application logic remains the same.
private void label1_Click_1(object sender, EventArgs e) {}
call on Page Load like:
Page_Load(...)
{
label1_Click_1(null, null);
}

Related

updated values are not getting stored in the textbox

protected void Page_Load(object sender, EventArgs e)
{
cnst = "Data Source=IBM369-R9WAKY5;Initial Catalog=anudatabase;Integrated Security=True";
cn = new SqlConnection(cnst);
cn.Open();
st = "select * from patient_db where unique_id = 123";
cmd = new SqlCommand(st, cn);
dr = cmd.ExecuteReader();
if (dr.Read())
{
Label9.Text = dr.GetString(1);
Label10.Text = dr.GetInt16(2).ToString();
Label11.Text = dr.GetString(6);
Label12.Text = dr.GetString(7);
TextBox1.Text = dr.GetString(3);
TextBox2.Text = dr.GetDecimal(4).ToString();
}
cn.Close();
}
//Button click function
protected void Button1_Click(object sender, EventArgs e)
{
cn.Open();
st = "update patient_db set address ='" + TextBox1.Text + "' ,phone=" + TextBox2.Text+"where unique_id=123";
cmd = new SqlCommand(st, cn);
int result2 = cmd.ExecuteNonQuery();
if (Convert.ToBoolean(result2))
{
result1.Text = "details updated successfully";
}
cn.Close();
}
After assigning the value to textbox from the database,if I type some other new value in the text box,it is not taking the new value,it still persists with the old value.May i know the reason and solution for this? thanks in advance
Write a method LoadData, move the code from page_load into this method. Then call this method from page_load wrapped in a if(!IsPostBack)-check. Call this method also from the button-click event handler after you've updated the values.
private void LoadData()
{
using (var cn = new SqlConnection("Data Source=IBM369-R9WAKY5;Initial Catalog=anudatabase;Integrated Security=True"))
{
cn.Open();
using(var cmd = new SqlCommand("select * from patient_db where unique_id = 123", cn))
using (var dr = cmd.ExecuteReader())
{
if (dr.Read())
{
Label9.Text = dr.GetString(1);
Label10.Text = dr.GetInt16(2).ToString();
Label11.Text = dr.GetString(6);
Label12.Text = dr.GetString(7);
TextBox1.Text = dr.GetString(3);
TextBox2.Text = dr.GetDecimal(4).ToString();
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
LoadData();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
// ... update
LoadData();
}
Important notes:
Also use the using-statement for every object implementing IDisposable like the connection or the datareader. On that way all unmanaged resources are disposed properly. Even in case of an error.
If 123 is just an example and actually is a value provided by the user use sql-parameters to prevent sql-injection. No, use them always.
Add IsPostBack control at Page_Load method. Because before Button_Click event Page_Load event firing.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
cnst = "Data Source=IBM369-R9WAKY5;Initial Catalog=anudatabase;Integrated Security=True";
cn = new SqlConnection(cnst);
cn.Open();
st = "select * from patient_db where unique_id = 123";
cmd = new SqlCommand(st, cn);
dr = cmd.ExecuteReader();
if (dr.Read())
{
Label9.Text = dr.GetString(1);
Label10.Text = dr.GetInt16(2).ToString();
Label11.Text = dr.GetString(6);
Label12.Text = dr.GetString(7);
TextBox1.Text = dr.GetString(3);
TextBox2.Text = dr.GetDecimal(4).ToString();
}
cn.Close();
}
}
You need to check page.Ispostback property in your page Load.
Here is your code.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
cnst = "Data Source=IBM369-R9WAKY5;Initial Catalog=anudatabase;Integrated Security=True";
cn = new SqlConnection(cnst);
cn.Open();
st = "select * from patient_db where unique_id = 123";
cmd = new SqlCommand(st, cn);
dr = cmd.ExecuteReader();
if (dr.Read())
{
Label9.Text = dr.GetString(1);
Label10.Text = dr.GetInt16(2).ToString();
Label11.Text = dr.GetString(6);
Label12.Text = dr.GetString(7);
TextBox1.Text = dr.GetString(3);
TextBox2.Text = dr.GetDecimal(4).ToString();
}
cn.Close();
}
}
When you click on button then it will first call PageLoad event. So it will again set your old value to textbox and then it will call update method. So Update method will update old value to database.

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.

Not able to get value from drop down list, c#

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.

update asp.net text box

I have problem with updating data.
Sample:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
string id = row.Cells[1].Text;
Response.Redirect("edit.aspx?id="+id);
}
after this code transition to another page with update cmd.
protected void Page_Load(object sender, EventArgs e)
{
DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
foreach (DataRowView drv in dv)
{
IDLBL.Text = drv["ID"].ToString();
Name.Text = drv["Name"].ToString();
SName.Text = drv["SecondName"].ToString();
Ocenka.Text = drv["Graduate"].ToString();
Klass.Text = drv["Class"].ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ARM_TSPConnectionString"].ConnectionString);
con.Open();
string upd = "UPDATE Info SET Name=#Name, SecondName=#SecondName, Graduate=#Graduate, Class=#Class WHERE ID=#ID";
SqlCommand cmd = new SqlCommand(upd, con);
cmd.Parameters.AddWithValue("#ID", IDLBL.Text);
cmd.Parameters.AddWithValue("#SecondName", SName.Text);
cmd.Parameters.AddWithValue("#Graduate", Ocenka.SelectedValue);
cmd.Parameters.AddWithValue("#Class", Klass.SelectedValue);
cmd.Parameters.AddWithValue("#Name", Name.Text);
cmd.ExecuteNonQuery();
Response.Redirect("main.aspx");
}
I clicked button, and was redirected to main page. But nothing else, update doesn't work. :(
where do I have a problem?
I don't really know where is the problem, but for sure you need to refactor your update statement using the IDisposable capabilities of the connection object, it shoul look like this:
using (SqlConnection connection = new SqlConnection(
ConfigurationManager.ConnectionStrings["ARM_TSPConnectionString"].ConnectionString))
{
string upd = "UPDATE Info SET Name=#Name, SecondName=#SecondName, Graduate=#Graduate, Class=#Class WHERE ID=#ID";
SqlCommand cmd = new SqlCommand(upd, connection);
cmd.Parameters.AddWithValue("#ID", IDLBL.Text);
cmd.Parameters.AddWithValue("#SecondName", SName.Text);
cmd.Parameters.AddWithValue("#Graduate", Ocenka.SelectedValue);
cmd.Parameters.AddWithValue("#Class", Klass.SelectedValue);
cmd.Parameters.AddWithValue("#Name", Name.Text);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
Your update sql query looks fine:
con.Open();
com.ExecuteNonQuery();
con.Close();
that is try using this function instead and debug it to see if there is a sql exception thrown.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ARM_TSPConnectionString"].ConnectionString);
string upd = "UPDATE Info SET Name=#Name, SecondName=#SecondName, Graduate=#Graduate, Class=#Class WHERE ID=#ID";
SqlCommand cmd = new SqlCommand(upd, con);
cmd.Parameters.AddWithValue("#ID", IDLBL.Text);
cmd.Parameters.AddWithValue("#SecondName", SName.Text);
cmd.Parameters.AddWithValue("#Graduate", Ocenka.SelectedValue);
cmd.Parameters.AddWithValue("#Class", Klass.SelectedValue);
cmd.Parameters.AddWithValue("#Name", Name.Text);
con.Open();
com.ExecuteNonQuery();
con.Close();
Response.Redirect("main.aspx");
}
catch (SqlException e)
{
}
}
UPDATE: Think I've realised why it's not working for you... you have a column called class... but class in sql server is a reserved keyword... so you must put square brackets around it ... like so
Edited the escaping (made a mistake as pointed out by Hans in the comment below)
string upd = "UPDATE Info SET Name=#Name, SecondName=#SecondName, Graduate=#Graduate, [Class]=#Class WHERE ID=#ID";
The problem was found.Just add in Page_Load if(!isPostBack)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
foreach (DataRowView drv in dv)
{
IDLBL.Text = drv["ID"].ToString();
Name.Text = drv["Name"].ToString();
SName.Text = drv["SecondName"].ToString();
Ocenka.Text = drv["Graduate"].ToString();
Klass.Text = drv["Class"].ToString();
}
}
Now, all working good.

grid view is not showing result

I want to bind GridView at run time when the DataSource is selected and when the user select a option from a DropDownList. But the selected table or connection is not made properly.
Please check the following code and give me the appropriate solution.
public partial class index : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection();
string option = "";
protected void Page_Load(object sender, EventArgs e)
{
option = selectProductdropdown.SelectedValue;
}
protected void Button1_Click(object sender, EventArgs e)
{
Label2.Text = option;
if (option == "Books")
{
Label3.Text = option;
conn.ConnectionString = ConfigurationManager.ConnectionStrings["booksconnectionstring"].ConnectionString;
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * from books", conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter reader = new SqlDataAdapter(cmd);
DataSet s = new DataSet();
reader.Fill(s);
GridView1.DataSource = s;
GridView1.DataBind();
conn.Close();
}
The problem is in your page_load event, where you are assigning a value to option. When you click the button, the page_load will call again and your value will reset.
it should be...
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
option = selectProductdropdown.SelectedValue;
}
OR it would be better if you do like..
if (selectProductdropdown.SelectedValue == "Books")
because you are probably emptying option at each page load.
Avoid the public variable string option = "";
Instead define the same in the Click Event and get the selected value there
option = selectProductdropdown.SelectedValue;// move to click event
Because when the button is clicked the dropdown would be reset (assuming you have not shown the dropdown bind code here)
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
option = selectProductdropdown.SelectedValue;
}
You had omitted this line:
cmd.ExecuteReader();
Place it between the statements, like this:
SqlCommand cmd = new SqlCommand("SELECT * from books", conn);
cmd.ExecuteReader(); // <-- HERE
cmd.CommandType = CommandType.Text;

Categories

Resources