How to make a bit false when user select checkbox in gridview - c#

Hi coder i have a search user page where i have a texbox, button and a gridview. Now when i enter name of the user and click on search button i get the detail of the user.
My database is like this
I already bind my gridview on page load so that i can also view the details of user in gridview like this:
Now in this gridview you can see a IsEnable header which have checkbox control. That Enable is a bit which is always true when user is created.
What i want is when user click on that checkbox that bit become false i try this on the rowdatabound but it give me object reference error can you guys tell me what i do to make my bit false when user select that checkbox
Please help me on this thanks in advance
Now this what i done now with my code now tell me how to update my enable bit from true to false on row update
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.GetGridData();
}
}
protected void BindGrid()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from CreateUser", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
GridView1.DataSource = ds;
GridView1.DataBind();
int columncount = GridView1.Rows[0].Cells.Count;
GridView1.Rows[0].Cells.Clear();
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
GridView1.Rows[0].Cells[0].Text = "No Records Found";
}
}
private void GetGridData()
{
con.Open();
string query = "Select * from CreateUser";
da = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
protected void btnSearchUser_Click(object sender, EventArgs e)
{
this.BindGrid();
}
protected void lnkdelete_Click(object sender, EventArgs e)
{
LinkButton lnkbtn = sender as LinkButton;
//getting particular row linkbutton
GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
//getting userid of particular row
int UserID = Convert.ToInt32(GridView1.DataKeys[gvrow.RowIndex].Value.ToString());
string FirstName = gvrow.Cells[0].Text;
con.Open();
SqlCommand cmd = new SqlCommand("delete from CreateUser where UserID=" + UserID, con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindGrid();
//Displaying alert message after successfully deletion of user
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + FirstName + " details deleted successfully')", true);
this.GetGridData();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//if (e.Row.RowType == DataControlRowType.DataRow)
//{
// //getting username from particular row
// string FirstName = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "FirstName"));
// //identifying the control in gridview
// LinkButton lnkbtnresult = (LinkButton)e.Row.FindControl("lnkdelete");
// //raising javascript confirmationbox whenver user clicks on link button
// lnkbtnresult.Attributes.Add("onclick", "javascript:return ConfirmationBox('" + FirstName + "')");
//}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GetGridData();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label userid= (Label)row.FindControl("lblUserID");
con.Open();
SqlCommand cmd = new SqlCommand("delete FROM CreateUser where UserID='" + Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString()) + "'", con);
cmd.ExecuteNonQuery();
con.Close();
BindGrid();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void GridView1_RowUpdating1(object sender, GridViewUpdateEventArgs e)
{
string query = string.Empty;
string userid = GridView1.DataKeys[e.RowIndex].Values["UserID"].ToString();
//Label id = GridView1.Rows[e.RowIndex].FindControl("lblUserID") as Label;
TextBox FirstName = GridView1.Rows[e.RowIndex].FindControl("txtFirstName") as TextBox;
TextBox LastName = GridView1.Rows[e.RowIndex].FindControl("txtLastName") as TextBox;
TextBox DomainID = GridView1.Rows[e.RowIndex].FindControl("txtDomainID") as TextBox;
TextBox EmailID = GridView1.Rows[e.RowIndex].FindControl("txtEmailID") as TextBox;
TextBox Password = GridView1.Rows[e.RowIndex].FindControl("txtPassword") as TextBox;
TextBox ConfirmPassword = GridView1.Rows[e.RowIndex].FindControl("txtConfirmPassword") as TextBox;
TextBox RoleType = GridView1.Rows[e.RowIndex].FindControl("txtRoleType") as TextBox;
CheckBox IsEnable = GridView1.Rows[e.RowIndex].FindControl("chkIsEnableEdit") as CheckBox;
//TextBox textadd = (TextBox)row.FindControl("txtadd");
//TextBox textc = (TextBox)row.FindControl("txtc");
GridView1.EditIndex = -1;
con.Open();
//SqlCommand cmd = new SqlCommand("SELECT * FROM detail", conn);
SqlCommand cmd = new SqlCommand("update CreateUser set FirstName='" + FirstName.Text + "',LastName='" + LastName.Text + "',DomainID='" + DomainID.Text + "',EmailID='" + EmailID.Text + "',Password='" + Password.Text + "',ConfirmPassword='" + ConfirmPassword.Text + "',RoleType='" + RoleType.Text + "',Enable='" + IsEnable.Checked + "' where UserID='" + userid + "'", con);
cmd.ExecuteNonQuery();
con.Close();
BindGrid();
//GridView1.DataBind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGrid();
}
}

Put some defensive coding in first, and find out where the object reference error is happening:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
var chk = (CheckBox)e.Row.FindControl("chkEnable");
if (chk == null || !chk.checked) return;
var userId =GridView1.DataKeys[row.RowIndex].Value as string;
if (string.IsNullOrWhiteSpace(userId)) return;
var query = "update CreateUser set Enable='False' where UserID='" + userid + "'";
cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
con.Close();
}
}
You can use the CheckChanged event:
<asp:GridView ID="GridView1" runat="server" onrowcommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkEnable" runat="server" AutoPostBack="true" OnCheckedChanged="ChkEnable_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And then update the database in CheckChanged event:
protected void ChkEnable_CheckedChanged(object sender, EventArgs e)
{
int selRowIndex = ((GridViewRow)(((CheckBox)sender).Parent.Parent)).RowIndex;
var userId = gridView.DataKeys[selRowIndex].Value as string;
if (string.IsNullOrWhiteSpace(userId)) return;
var checkBox = gridView.Rows[selRowIndex].FindControl("chkEnable") as CheckBox;
if (checkBox == null) return;
var query = "update CreateUser set Enable= #Enabled where UserID='" + userid + "'";
cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("Enabled", checkBox.Checked);
cmd.ExecuteNonQuery();
con.Close();
}

First of all why are you doing it on RowDataBound event ? RowDataBound occurs when a row is
bounded to gridview but here we have to update gridview rows.
If you have to update your rows you can do it on RowUpdating command .
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Checkbox chkbx = ((Checkbox)(row.Cells[8].Controls[0]));
bool IsChecked =chkbx.Checked ;
//You can write your update command here.
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox MyName= (TextBox)e.Row.FindControl("FirstName");
string name = Myname.text;
//For checkbox
Checkbox chkbx = (Checkbox)e.Row.FindControl("IsEnabled");
if(chkbx.Checked ==true)
{
// do your stuff for checkbox checked.
}
else
{
// do your stuff if checkbox is not selected
}
}
}

Finally i got my answer thanks for your reply guys
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.GetGridData();
}
}
protected void BindGrid()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from CreateUser", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
GridView1.DataSource = ds;
GridView1.DataBind();
int columncount = GridView1.Rows[0].Cells.Count;
GridView1.Rows[0].Cells.Clear();
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
GridView1.Rows[0].Cells[0].Text = "No Records Found";
}
}
private void GetGridData()
{
con.Open();
string query = "Select * from CreateUser";
da = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
protected void btnSearchUser_Click(object sender, EventArgs e)
{
this.BindGrid();
}
protected void lnkdelete_Click(object sender, EventArgs e)
{
LinkButton lnkbtn = sender as LinkButton;
//getting particular row linkbutton
GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
//getting userid of particular row
int UserID = Convert.ToInt32(GridView1.DataKeys[gvrow.RowIndex].Value.ToString());
string FirstName = gvrow.Cells[0].Text;
con.Open();
SqlCommand cmd = new SqlCommand("delete from CreateUser where UserID=" + UserID, con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindGrid();
//Displaying alert message after successfully deletion of user
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + FirstName + " details deleted successfully')", true);
this.GetGridData();
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GetGridData();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label userid= (Label)row.FindControl("lblUserID");
con.Open();
SqlCommand cmd = new SqlCommand("delete FROM CreateUser where UserID='" + Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString()) + "'", con);
cmd.ExecuteNonQuery();
con.Close();
BindGrid();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void GridView1_RowUpdating1(object sender, GridViewUpdateEventArgs e)
{
string query = string.Empty;
string userid = GridView1.DataKeys[e.RowIndex].Values["UserID"].ToString();
//Label id = GridView1.Rows[e.RowIndex].FindControl("lblUserID") as Label;
TextBox FirstName = GridView1.Rows[e.RowIndex].FindControl("txtFirstName") as TextBox;
TextBox LastName = GridView1.Rows[e.RowIndex].FindControl("txtLastName") as TextBox;
TextBox DomainID = GridView1.Rows[e.RowIndex].FindControl("txtDomainID") as TextBox;
TextBox EmailID = GridView1.Rows[e.RowIndex].FindControl("txtEmailID") as TextBox;
TextBox Password = GridView1.Rows[e.RowIndex].FindControl("txtPassword") as TextBox;
TextBox ConfirmPassword = GridView1.Rows[e.RowIndex].FindControl("txtConfirmPassword") as TextBox;
TextBox RoleType = GridView1.Rows[e.RowIndex].FindControl("txtRoleType") as TextBox;
CheckBox IsEnable = GridView1.Rows[e.RowIndex].FindControl("chkIsEnableEdit") as CheckBox;
//TextBox textadd = (TextBox)row.FindControl("txtadd");
//TextBox textc = (TextBox)row.FindControl("txtc");
GridView1.EditIndex = -1;
con.Open();
//SqlCommand cmd = new SqlCommand("SELECT * FROM detail", conn);
SqlCommand cmd = new SqlCommand("update CreateUser set FirstName='" + FirstName.Text + "',LastName='" + LastName.Text + "',DomainID='" + DomainID.Text + "',EmailID='" + EmailID.Text + "',Password='" + Password.Text + "',ConfirmPassword='" + ConfirmPassword.Text + "',RoleType='" + RoleType.Text + "',Enable='" + IsEnable.Checked + "' where UserID='" + userid + "'", con);
cmd.ExecuteNonQuery();
con.Close();
BindGrid();
//GridView1.DataBind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGrid();
}
}

Related

How to store the value of a cell from grid view to database using the select command?

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
GridViewRow gv = GridView1.SelectedRow;
Session["m_email"] = gv.Cells[3];
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
con.Open();
string insert = "insert into Service_Info values(#c_email,#email,#first_name,#last_name,#contact,#licenseno,#street,#landmark,#pincode)";
SqlCommand cmd = new SqlCommand(insert, con);
cmd.Parameters.AddWithValue("#c_email", Session["user"].ToString());
cmd.Parameters.AddWithValue("#email",Session["m-email"].ToString());
cmd.Parameters.AddWithValue("#first_name", Session["user"].ToString());
cmd.Parameters.AddWithValue("#last_name", Session["user"].ToString());
cmd.Parameters.AddWithValue("#contact", Session["user"].ToString());
cmd.Parameters.AddWithValue("#licenseno", Session["user"].ToString());
cmd.Parameters.AddWithValue("#street", StreetText.Text);
cmd.Parameters.AddWithValue("#landmark", LandmarkText.Text);
cmd.Parameters.AddWithValue("#pincode", PincodeText.Text);
cmd.ExecuteNonQuery();
Label6.Visible = true;
Label6.Text = "Successfull...";
con.Close();
}
}
I want to store the value of a cell from the grid view to the database. I only want to store only the email cell value not all from grid view. But I am not getting a way to do so.
Try the following code:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int selectedRowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow gv = GridView1.Rows[selectedRowIndex];
// Rest of the code
}
}

Get value of the third column in a table in selectedindex changed event of dropdown list in asp.net

This is my code to display table value to a DropDownList.
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Conn"].ConnectionString))
{
con.Open();
string str="SELECT ItemOne,ItemTwo,ItemThree FROM tableItem";
using (SqlCommand cmd = new SqlCommand(str, con))
{
SqlDataAdapter dA=new SqlDataAdapter(cmd);
dA.Fill(dT);
DropDownList1.DataSource = dT;
DropDownList1.DataValueField = "ItemTwo";
DropDownList1.DataTextField = "ItemOne";
DropDownList1.DataBind();
}
This is to display the selected value of DropDownList to a TextBox.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedValue.ToString();
TextBox2.Text = //Get the value of ItemThree here
}
My problem is: How will I display the column value of ItemThree in another TextBox.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedValue.ToString();
TextBox2.Text = DropDownList1.Items[2].ToString(); // 2 is your index
}
Another way of doing this
var connectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
var sql = "SELECT ItemOne, ItemTwo, ItemThree FROM tableItem";
using (var table = new DataTable) {
using (var adapter = new SqlDataAdapter(sql, connectionString)
adapter.Fill(table);
foreach (DataRow dr in table.Rows)
DropDownList1.Items.Add(new ListItem(dr["ItemTwo"], dr["ItemTwo"]) {
Tag = dr["ItemThree"]
});
}
Then from the event handler
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedValue.ToString();
TextBox2.Text = DropdownList1.SelectedItem.Tag.ToString();
}

search, edit and delete using gridview with sql server in c#

i am using Gridview buttons to edit and delet records from sql DB , the problem that i use specific criteris (search by textbox and combobox) then i do edit for the results here is the code i use :
protected void Page_Load(object sender, EventArgs e)
{
conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["zamzammembersConnectionString"].ConnectionString);
if (!IsPostBack)
{
bind();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
bind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lbl = (Label)row.FindControl("lblid");
TextBox textname = (TextBox)row.FindControl("textbox1");
TextBox textmarks = (TextBox)row.FindControl("textbox2");
GridView1.EditIndex = -1;
conn.Open();
SqlCommand cmd = new SqlCommand("update emp set marks=" + textmarks.Text + " , name='" + textname.Text + "' where rowid=" + lbl.Text + "", conn);
cmd.ExecuteNonQuery();
conn.Close();
bind();
}
public void bind()
{
conn.Open();
SqlCommand com = new SqlCommand("select zam_pcinfo.employe_name as Name , zam_location.locationname as Location from zam_pcinfo inner join zam_location on zam_pcinfo.location_id = zam_location.locationId where zam_pcinfo.employe_name like #name or zam_location.locationname like #locationname;", conn);
com.Parameters.AddWithValue("#name", SqlDbType.VarChar).Value = nametxt.Text;
com.Parameters.AddWithValue("#locationname", SqlDbType.VarChar).Value = locationdrop.SelectedValue;
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
conn.Close();
}
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lbldeleteID = (Label)row.FindControl("lblid");
conn.Open();
SqlCommand cmd = new SqlCommand("delete emp where rowid=" + lbldeleteID.Text + "", conn);
cmd.ExecuteNonQuery();
conn.Close();
bind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bind();
}
}
when i try to make the same code in bind() method to a button it works fine but i couldn't do edit and delete on it . how can i make edit and delete in gridview with data that i search for ?

Updating a row in a Template field gridview by using Commandfiled buttons?

what is wrong with the code here... i am trying to update the values fetched in a row of a grid view by an edit,update,cancel command field button.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label lblid = (Label)GridView1.Rows[e.RowIndex].FindControl("Elblid");
TextBox txtuser = (TextBox)GridView1.Rows[e.RowIndex].FindControl("EtxtUserName");
TextBox txtpass = (TextBox)GridView1.Rows[e.RowIndex].FindControl("EPassword");
if (lblid.Text != "" || lblid.Text != null)
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["con"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("Update Login set UserName='" + txtuser.Text + "',Password='" + txtpass.Text + "' Where Id=" + lblid.Text, con);
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
FillGrid();
}
This was the error thrown :
PS: when is set the event validation to be false in the page directives. this error disappeared but the code did nothing it was intended to.
what error it is showing??
try this
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lblid = (Label)row.FindControl("Elblid");
TextBox txtuser = (TextBox)row.FindControl("EtxtUserName");
TextBox txtpass = (TextBox)row.FindControl("EPassword");
}

sorting on searched records not working

I am having problem in sorting the searched records in a gridview to ascending and descending directions. I have applied the following code to normal gridview (all records) and it is working all fine but when I try to search any records from all records, and try to sort those searched records, following code neither performs any actions nor throws any errors: Following code is applied for sorting:
protected void GridView2_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView1(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView1(sortExpression, ASCENDING);
}
}
private void SortGridView1(string sortExpression, string direction)
{
DataTable dt = SearchTable().Tables[0];
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
GridView2.DataSource = dv;
GridView2.DataBind();
}
Search function code is:
public DataSet SearchTable()
{
string sql1 = "SELECT * from dbo.Documents1";
bool flag = false;
if (!txtRef.Text.Equals(""))
{
if (flag == false)
{
sql1 = sql1 + " where Ref LIKE N'%" + txtRef.Text + "%'";
flag = true;
}
else
{
sql1 = sql1 + " and Ref LIKE N'%" + txtRef.Text + "%'";
}
}
if (!txtSubject.Text.Equals(""))
{
if (flag == false)
{
sql1 = sql1 + " where Subject LIKE N'%" + txtSubject.Text + "%'";
flag = true;
}
else
{
sql1 = sql1 + " and Subject LIKE N'%" + txtSubject.Text + "%'";
}
}
}
using (SqlConnection con = new SqlConnection("Data Source=MEHDI-PC\\SQLEXPRESS;Initial Catalog=PIMS;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = sql1 + ";";
//cmd.CommandType = CommandType.StoredProcedure;
con.Open();
//dataset object to get all select statement results
DataSet ds = new DataSet();
//sql dataadoptor to fill dataset
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
adp.Fill(ds);
}
if (con.State == ConnectionState.Open)
{
con.Close();
}
return ds;
}
}
}
PageLoad Event function is:
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = rpt.Documents1s.ToList();
GridView1.DataBind();
if (!IsPostBack)
{
BindGrid();
MultiView1.SetActiveView(vHome);
btnBacktoHome.Visible = false;
lblStatus.Visible = false;
}
}
I cant understand where I am going wrong. when clicked on a column to sort, it took me out of searched records and sorted "All-Records" which are placed in GridView1 while searched-records are placed in GridView2 as shown in the code. what I am failed to understand is, why programs jumps to GridView1 and sort all-records there when I click to click to sort searched-records in GridView2. Any help will be much appreciated. Thanks in advance.
Did you use the gridview binding code in inside of !ISPostBack ? like
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//Grid Binding code
}
}
Edit for you page load code(Must add the databind in inside of !IsPostBack)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = rpt.Documents1s.ToList();
GridView1.DataBind();
BindGrid();
MultiView1.SetActiveView(vHome);
btnBacktoHome.Visible = false;
lblStatus.Visible = false;
}
}

Categories