Gridview does not view the results in asp.net - asp.net

I am trying to show the search results on a gridview on the same search page in asp.net. Here is the UI:
And here is my code:
protected void Page_Load(object sender, EventArgs e)
{
searchResults.DataBind();
}
protected void BClassSearch_Click(object sender, EventArgs e)
{
// if (!IsPostBack)
//{
SqlConnection con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
con.Open();
string selected = lbCourseListBox.SelectedValue;
if(selected!="" && Tcoursenumber.Text!="")
{
string query = "select [CRN],[CourseCode],[CourseNumber],[Credit],[CourseName],[Capacity],[InstructorName] from CourseTable where CourseCode='" + lbCourseListBox.SelectedValue+"' and CourseNumber = '" + Tcoursenumber.Text+"'";
SqlDataAdapter adap = new SqlDataAdapter(query, con);
DataTable tab = new DataTable();
adap.Fill(tab);
searchResults.DataSource = tab;
searchResults.DataBind();
}
else if (selected != "" && Tcoursenumber.Text == "")
{
string query = "select [CRN],[CourseCode],[CourseNumber],[Credit],[CourseName],[Capacity],[InstructorName] from CourseTable where CourseCode='" + lbCourseListBox.SelectedValue;
SqlDataAdapter adap = new SqlDataAdapter(query, con);
DataTable tab = new DataTable();
adap.Fill(tab);
searchResults.DataSource = tab;
searchResults.DataBind();
}
else if (selected == "" && Tcoursenumber.Text != "")
{
string query = "select [CRN],[CourseCode],[CourseNumber],[Credit],[CourseName],[Capacity],[InstructorName] from CourseTable where CourseNumber='" + Tcoursenumber.Text;
SqlDataAdapter adap = new SqlDataAdapter(query, con);
DataTable tab = new DataTable();
adap.Fill(tab);
searchResults.DataSource = tab;
searchResults.DataBind();
}
//}
Response.Redirect("SearchCourse.aspx");
}
The problem is, no search result is displayed in gridview. Can anyone help me with this?
Thanks

Remove Response.Redirect("SearchCourse.aspx"); at the end of button click
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// do you want to bind something in first time load? then load it here
// searchResults.DataSource = tab;
searchResults.DataBind();
}
}
You don't want to call the Response.Redirect to the same page because when you click on button it will postback the page. if you call Response.Redirect it will load new page and you will lost all the control states in the page.

Related

!IsPostBack returns always true

I am trying to implement search operation for my gridview.When I load my page first time !IsPostBack works fine but when I click on the search button my page loads again and !IsPostBack returns true value.So, I was not able to perform my search operation
this is my code.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
((Label)Master.FindControl("Label1")).Text = (string)Session["sname"];
fillData();
}
}
public void fillData()
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM EBR_Supplier where DeleteFlag=" + 0 + " ORDER BY RowId ASC", con);
SqlDataAdapter adap = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adap.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
fillData();
}
protected void search_Click(object sender, EventArgs e)
{
string id = txtid.Text;
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM EBR_Supplier where DeleteFlag=" + 0 + " and SupplierId='" + id + "' ORDER BY RowId ASC", con);
SqlDataAdapter adap = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adap.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
I have found the solution myself I have a form control on my master page.I removed that it helped me.I thank you all for giving time to my question.

lable is not showing any output for the dropdown list selection

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LibraryConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlbookavail.Items.Add(new ListItem("select", "-1"));
ddlbookavail.AppendDataBoundItems = true;
SqlCommand cmd = new SqlCommand("select * from tblbookinfo", con);
con.Open();
ddlbookavail.DataSource = cmd.ExecuteReader();
ddlbookavail.DataTextField = "Name";
ddlbookavail.DataValueField = "Id";
ddlbookavail.DataBind();
con.Close();
txtdate.Text = DateTime.Now.Date.ToString("dd/MM/yyyy");
}
in my design page i put the sql datasource from data and got this connection srting

I have error in updating records in database sql server

I have a problem : I have page for insert data into database , and the same page for update data based on query string for each item , the problem when i update the fields from textbox(s) , the same data is returned to update: the same data updated in database from textbox in page_load !!
In Page_Load
con.Open();
//For edit items
if (Request.QueryString["id"] != null)
{
Page.Title = "Edit Items";
DataTable dt = Get_Items(Request.QueryString["id"].ToString());
txt_item_name.Text = dt.Rows[0]["name"].ToString();
txt_end_date.Text = dt.Rows[0]["endDate"].ToString();
Btn_addItem.Text = "Edit item";
}
protected void Btn_addItem_Click(object sender, EventArgs e)
{
if (Btn_addItem.Text.Equals("Add Item"))
{
SqlCommand cmd = new SqlCommand("addedit", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#item_id", "-1");
cmd.Parameters.AddWithValue("#name", txt_item_name.Text);
cmd.Parameters.AddWithValue("#endDate", txt_end_date.Text);
con.Open();
cmd.ExecuteNonQuery();
lbl_msg.Text = "Item added....";
con.Close();
}
else
{
SqlCommand cmd = new SqlCommand("addedit", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#item_id", Request.QueryString["id"]);
cmd.Parameters.AddWithValue("#name", txt_item_name.Text);
cmd.Parameters.AddWithValue("#endDate", txt_end_date.Text);
con.Open();
cmd.ExecuteNonQuery();
lbl_msg.Text = "Item edited....";
con.Close();
}
}
If I understand your question correctly "You are not able to update the DB with the new value you enter in the textboxes. Its updating the DB with the old value again".
You need to check for !IsPostback in your Page_Load as the code for binding the textboxes from DB will be called before Btn_addItem_Click during postback and it will set the value of textboxes back to the old value from DB. See below updated code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
con.Open();
//For edit items
if (Request.QueryString["id"] != null)
{
Page.Title = "Edit Items";
DataTable dt = Get_Items(Request.QueryString["id"].ToString());
txt_item_name.Text = dt.Rows[0]["name"].ToString();
txt_end_date.Text = dt.Rows[0]["endDate"].ToString();
Btn_addItem.Text = "Edit item";
}
}
}
Hope it helps.

Object reference not set to an instance of an object in gridview in asp.net

I am getting this error on a row command in my gridview. Here is the code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = University.GetConnectionString();
con.Open();
string query = "select [CourseCode], [CourseNumber], [CourseName], [CRN], [Level], [Credit] from CourseTable where Term='" + MyGlobals.currentTerm + " " + MyGlobals.currentYear + "'";
SqlDataAdapter adap = new SqlDataAdapter(query, con);
DataTable tab = new DataTable();
adap.Fill(tab);
gCourses.DataSource = tab;
gCourses.DataBind();
}
}
protected void gCourses_RowCommand(object sender, GridViewCommandEventArgs e)
{
// *** Retreive the DataGridRow
int row = -1;
int.TryParse(e.CommandArgument as string, out row);
GridViewRow gdrow = gCourses.Rows[row];
DataRow dr = ((DataTable)this.gCourses.DataSource).Rows[gdrow.DataItemIndex];
string crn = dr["CRN"].ToString();
}
.
DataRow dr = ((DataTable)this.gCourses.DataSource).Rows[gdrow.DataItemIndex];
line throws the exception.
What is wrong here? Thanks
Remove the
if (!isPostback)
from your page load

Dynamically added checkboxs are not working in asp.net using c#?

i am adding multiple checkboxes in my asp.net page by doing this:
public static CheckBox[] chck;
on pageload:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
con.Open();
SqlCommand cmd = new SqlCommand("select count(CompanyName) from Stock_Company");
cmd.Connection = con;
comno = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
chck = new CheckBox[comno];
}
}
now i have a function which is generating the checkboxes :
public void generatecheckbox1()
{
con.Open();
SqlCommand cmd = new SqlCommand("select CompanyName from Stock_Company");
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
con.Close();
for (int i = 0; i < dt.Rows.Count; i++)
{
chck[i] = new CheckBox();
chck[i].ID = "chck" + Convert.ToString(i);
chck[i].Text = dt.Rows[i]["CompanyName"].ToString();
pnlcom1.Controls.Add(chck[i]);
pnlcom1.Controls.Add(new LiteralControl("<br />"));
}
}
and i am calling this on a combobox event:
protected void ddluserwebser_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddluserwebser.SelectedItem.Text == "Custom")
{
generatecheckbox1();
}
}
as far as this all are working fine ... but in a button click i want to get the select checkbox's text which i am not getting
i made a function :
public string getbsecompany()
{
string companyname = "";
string bsetricker = "";
con.Open();
SqlCommand cmd = new SqlCommand("select CompanyName from Stock_Company");
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
con.Close();
for (int i = 0; i < dt.Rows.Count; i++)
{
if (chck[i].Checked == true) **THE PROBLEM IS HERE**
{
companyname = chck[i].Text;
con.Open();
SqlCommand cmdd = new SqlCommand("select BSETickerCode from Stock_Company where CompanyName='" + companyname + "'");
cmdd.Connection = con;
bsetricker += bsetricker + "+" + cmdd.ExecuteScalar();
con.Close();
}
}
return bsetricker;
}
and i am calling it here:
protected void btnusersave_Click(object sender, EventArgs e)
{
string bsetricker = "";
bsetricker = getbsecompany();
}
the problem is i am not getting the checked box's text. when i am checking if (chck[i].Checked == true) i am gettin false and all checkboxes are checked.
What should i do now?
any help
The dynamic controls should added to page in On_Init() for each time if you want it display in page.
Else there's nothing you can get.
Plus, better not use a static value to contains checkBox List, it will cause problem when multi user access same page. You can save them in session or try this.Form.FindControls()

Resources