grid view is not showing result - c#

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;

Related

Attempting to get a count of records from gridview based on a selected date from dropdownlist but cant?

The problem lies that upon selection of the date in the dropdown it will give the count of the LAST selection, not the current.
I am a novice and the only thing I can think of is some type of postback issue? The gridview populates fine with the records selected by the DDL, so I just cant get my head around why the count that is rendered is the previous selection.
protected void ddlClassDate_SelectedIndexChanged(object sender, EventArgs e)
{
lblRecordCounter.Text = "";
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
string connectionString = ConfigurationManager.ConnectionStrings["gescdb"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("SELECT (*) FROM gescdb" +
"WHERE ClassDate=" + ddlClassDate.Text, conn);
try
{
conn.Open();
reader = comm.ExecuteReader();
GridRegistrants.DataSource = reader;
GridRegistrants.DataBind();
reader.Close();
}
catch
{
}
finally
{
conn.Close();
lblRecordCounter.Text = GridRegistrants.Rows.Count.ToString();
}
In your Page_Load method you do the same, right? You have to move that code into following block:
if (!IsPostBack){
//Your code is here
}
Your DropDownList:
<asp:DropDownList ID="ddlClassDate" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlClassDate_SelectedIndexChanged" />
Your code behind:
protected void Page_Load(object sender, EventArgs e){
if (!IsPostBack){
BindDDL();
BindGrid(ddlClassDate.SelectedValue);
}
}
protected void BindDDL(){
//Bind Your dropdownlist here
}
protected void BindGrid(string ddate){
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["gescdb"].ConnectionString);
SqlCommand comm = new SqlCommand("select * from gescdb where ClassDate = #date", conn);
comm.Parameters.Add("#date", SqlDbType.VarChar).Value = ddate;
try
{
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
sda.Fill(ds);
GridRegistrants.DataSource = ds;
GridRegistrants.DataBind();
}
catch
{
//...
}
finally
{
conn.Close();
}
}
protected void ddlClassDate_SelectedIndexChanged(object sender, EventArgs e){
BindGrid(ddlClassDate.SelectedValue);
}

Having issue regarding to checklistbox

I have a checkedListBox and a TextBox...When I Checked item in the checkedListBox it shows the value of the respective item in the TextBox...When I Checked multiple items in the checkedListBox it shows the values of the respective items in the TextBox separating by {,}"Comma"
Now my question is that when I unchecked the item in the textBox it must remove the value of respective unchecked items from the textBox ...also please tell me how do I remove "Comma"{,} from the end of the text box programmatically
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection("Data Source=.;Initial Catalog=email_client;Integrated Security=True");
SqlCommand command = new SqlCommand("Select * FROM address_book ", connection);
try
{
connection.Open();
{
SqlDataReader drd = command.ExecuteReader();
while (drd.Read())
{
this.checkedListBox1.Items.Add(drd.GetString(0).ToString());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
connection.Close();
}
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=email_client;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from address_book where name='" + checkedListBox1.Text + "'", con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text += Convert.ToString(dr["id"] + ",");
}
dr.Close();
}
private void textBox1_Enter(object sender, EventArgs e)
{
ToolTip tt = new ToolTip();
tt.SetToolTip(textBox1, "sorry");
}
}
First of all, you should not use SelectedIndexChanged event if you'd like to show "checked" items. Use ItemCheck instead:
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
Then use CheckedListBox.CheckedItems to retrive all items which are checked:
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
StringBuilder stringBuilder = new StringBuilder();
foreach (var item in checkedListBox1.CheckedItems)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=email_client;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand(string.Format("select * from address_book where name='{0}'", item), con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
stringBuilder.Append(Convert.ToString(dr["id"] + ","));
}
dr.Close();
}
textBox1.Text = stringBuilder.ToString().TrimEnd(',');
}
Remember use string.TrimEnd() to trim the last comma.
Well, this is not the most effective way to do this, because you need to go through each checked item when one of them changed. You could use a Dictionary to maintain name-id pairs -- at least it is no need to execute SQL queries when you unchecked an item, right? :)
To remove ,
textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 1);
But I would ideally keep my dr["id"] in a List and create a small function that iterates through the list and return comma separated string. Adding and Removing items should take place in that collection.

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.

How to get value from database to a label?

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

Data doesn't get updated when an item is chosen from drop down list

I would like ask if you could help me with my codes as I don't get the result that I want which is to load the details of a particular paper from drop down list.
Currently, when the page loads, the details of the selected item will load up. But when I try to choose another item from the drop down list, corresponding details won't show up, the previous one still remains instead.
Under the properties of drop down list, I also set autopostback to yes so that it will automatically load the corresponding details of the item selected.
Please see codes below
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetPaper();
GetInk();
GetPaperDetails(ddlPaperName.SelectedItem.Value);
//pnlPrinting.Visible = true;
}
}
protected void btnCompute_Click(object sender, EventArgs e)
{
}
protected void btnCancel_Click(object sender, EventArgs e)
{
}
private void GetPaper()
{
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.Text;
com.CommandText =
"SELECT * FROM Papers";
SqlDataReader data = com.ExecuteReader();
ddlPaperName.DataSource = data;
ddlPaperName.DataValueField = "PaperID";
ddlPaperName.DataTextField = "PaperName";
ddlPaperName.DataBind();
data.Close();
con.Close();
}
private void GetPaperDetails(string paper)
{
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.Text;
com.CommandText =
"SELECT * FROM Papers WHERE PaperID=" + paper;
SqlDataReader data = com.ExecuteReader();
while (data.Read())
{
lblPaperPrice.Text = data["PaperPrice"].ToString();
lblDescription.Text = data["PaperDescription"].ToString();
lblSpecification.Text = data["PaperSpecification"].ToString();
imgPaper.ImageUrl = "../" + data["PaperImage"].ToString();
}
data.Close();
con.Close();
}
private void GetInk()
{
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.Text;
com.CommandText =
"SELECT * FROM Inks";
SqlDataReader data = com.ExecuteReader();
ddlPaperName.DataSource = data;
ddlPaperName.DataValueField = "InkID";
ddlPaperName.DataTextField = "InkName";
ddlPaperName.DataBind();
while (data.Read())
{
lblInkPrice.Text = data["InkPrice"].ToString();
}
data.Close();
con.Close();
}
protected void ddlPaperName_SelectedIndexChanged(object sender, EventArgs e)
{
GetPaperDetails(ddlPaperName.SelectedItem.Value);
}
Looking forward to your feedback here. Thanks!
Set AutoPostBack property to true of your drop down list.
us this code, for that,
if (!IsPostBack == true)
{
drpdownaccountnamebind();
drpdowncountrynamebind();
}
i hope this will be helpful,

Categories

Resources