asp.net clear row selection for Multiple Grid with Single Button Click - asp.net

Hi Friends i have created a single asp.net page(c#) with multiple grid view to display records. I have multiple command button to show records in these grid.
I am using single button to clear the row selection in grid but it is not working.
Please help me...
protected void btnClearGridSelection_Click(object sender, EventArgs e)
{
if (GridView1.Visible == true)
{
GridView1.SelectedIndex = -1;
}
if (GridView1.Visible == true)
{
GridViewSearch.SelectedIndex = -1;
}
if (GridView1.Visible == true)
{
GridViewState.SelectedIndex = -1;
}
if (GridView1.Visible == true)
{
GridViewDistrict.SelectedIndex = -1;
}
if (GridView1.Visible == true)
{
GridViewType.SelectedIndex = -1;
}
if (GridView1.Visible == true)
{
GridViewEmployee.SelectedIndex = -1;
}
}
//---------------------updating my question with new problem-------------
Now i am able to to clear the selection from row but facing new problem.......When i am clicking on show(to show results state wise) button it is showing results and also clearing the selection when clicking on clear selection button with no problems....but when i click on another show button(to show results district wise) to show results it is showing results but when i select the row and click on clear selection button it is showing both grid with records......please help how to hide state Grid when i am Clicking on Clear Selection Button while using District grid......i am posting the code which i am using on Button Click....
.......clear selection....Button click:
protected void btnClearGridSelection_Click(object sender, EventArgs e)
{ GridView1.SelectedIndex = -1;
GridViewSearch.SelectedIndex = -1;
GridViewState.SelectedIndex = -1;
GridViewDistrict.SelectedIndex = -1;
GridViewType.SelectedIndex = -1;
GridViewEmployee.SelectedIndex = -1;
}
.......State Grid....Button click:
protected void btnState_Click(object sender, EventArgs e)
{
GridView1.Visible = false;
//GridViewState.Visible = true;
GridViewDistrict.Visible = false;
GridViewSearch.Visible = false;
GridViewType.Visible = false;
GridViewEmployee.Visible = false;
btnClearGridSelection.Visible = true;
string d2 = ddlState.Text;
string strquery = "select * from tblAsset2 where v_State=#d2";
if (con.State != ConnectionState.Closed)
{
con.Close();
}
con.Open();
try
{
SqlCommand cmd = new SqlCommand(strquery, con);
cmd.Parameters.AddWithValue("#d2", d2);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridViewState.DataSource = ds;
GridViewState.DataBind();
int rowCount = GridViewState.Rows.Count;
if (rowCount <= 0)
{
Label67.Visible = true;
GridViewState.Visible = false;
Label67.Text = "Sorry!....Records not found.";
}
else
{
GridViewState.Visible = true;
Label67.Visible = false;
}
}
catch (Exception ex)
{
Response.Write(ex);
}
finally
{
con.Close();
}
}
....................District Grid....Button click:
protected void btnDistrict_Click(object sender, EventArgs e)
{
GridView1.Visible = false;
GridViewDistrict.Visible = false;
//GridViewDistrict.Visible = true;
GridViewSearch.Visible = false;
GridViewType.Visible = false;
GridViewEmployee.Visible = false;
btnClearGridSelection.Visible = true;
string d2 = ddlDistrict.Text;
string strquery = "select * from tblAsset2 where v_District=#d2";
if (con.State != ConnectionState.Closed)
{
con.Close();
}
con.Open();
try
{
SqlCommand cmd = new SqlCommand(strquery, con);
cmd.Parameters.AddWithValue("#d2", d2);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridViewDistrict.DataSource = ds;
GridViewDistrict.DataBind();
int rowCount = GridViewDistrict.Rows.Count;
if (rowCount <= 0)
{
Label67.Visible = true;
GridViewDistrict.Visible = false;
Label67.Text = "Sorry!....Records not found.";
}
else
{
GridViewDistrict.Visible = true;
Label67.Visible = false;
}
}
catch (Exception ex)
{
Response.Write(ex);
}
finally
{
con.Close();
}
}

I resolved my problem and it may help someone else so i am posting it.. i have written wrong line:- GridViewState.Visible = true; // i have commented this line and error gone
protected void GridViewState_RowCreated(object sender, GridViewRowEventArgs e)
{
GridViewState.Visible = true; // i have commented this line and error gone
}

Related

How to add data from one grid view to another grid view using a button Asp.net

I'm attempting to add details from one gridview to another gridview on the same page; however I'm not see the gridview (not visible). Not sure exactly what is causing that because visible is set to true in properties window.
protected void btnAssign_Click(object sender, EventArgs e)
{
DataRow drow;
DataTable dt = SetDataTable();
drow = dt.NewRow();
//GridView1.Rows.Add(1);
int row = GridView1.Rows.Count - 1;
drow["Customer Name"] = GridView1.Rows[row].Cells[0].Text;
drow["Invoice #"] = GridView1.Rows[row].Cells[1].Text;
drow["Invoice Qty"] = GridView1.Rows[row].Cells[2].Text;
//drow["Salary"] = textBox4.Text.Trim();
dt.Rows.Add(drow);
BindGrid(dt);
btnDelete.Visible = true;
}
private DataTable SetDataTable()
{
DataTable dt = new DataTable();
try
{
DataColumn dcol = new DataColumn("Customer Name", typeof(System.String));
dt.Columns.Add(dcol);
dcol = new DataColumn("Invoice #", typeof(System.String));
dt.Columns.Add(dcol);
dcol = new DataColumn("Invoice Qty", typeof(System.String));
dt.Columns.Add(dcol);
}
catch (Exception ex)
{
}
return dt;
}
private void BindGrid(DataTable dt)
{
try
{
if (dt.Rows.Count > 0)
{
GridView2.DataSource = dt;
}
else { }
}
catch (Exception ex)
{
}
}

checkboxlist selectedindexchanged event c# not working

I've got a checkboxlist on my asp.net page. I'm populating it with countries. I've added a "SelectedIndexChanged" event that is supposed to check that if one of the selected countries is Africa, it should make a textbox visible, otherwise visible=false if it is not selected. I have changed the AutoPostback to true. But the problem that I'm having is that it is not doing an autopostback (it's not going into the method at all). Could somebody please help me on this?
This is what I've done:
<div id="div1" style="overflow-x:auto; width:100%; max-width:100%; height:150px; max-height:150px;" runat="server">
<asp:CheckBoxList ID="lstLocations" CssClass="CheckBoxList" runat="server" Width="40%" Height="100%" AutoPostBack="True" OnSelectedIndexChanged="lstLocations_SelectedIndexChanged" >
</asp:CheckBoxList>
</div>
Populating the checkboxlist:
private void CreateRegionList()
{
lstLocations.Items.Clear();
cn = new SqlConnection(GetConnectionString());
SqlCommand myCmd = new SqlCommand("SELECT ID, Region FROM CanonSALeads_Region ORDER BY Region", cn);
cn.Open();
SqlDataReader myReader = myCmd.ExecuteReader();
lstLocations.AutoPostBack = false;
lstLocations.CellPadding = 5;
lstLocations.CellSpacing = 5;
lstLocations.RepeatColumns = 1;
lstLocations.RepeatDirection = RepeatDirection.Vertical;
lstLocations.RepeatLayout = RepeatLayout.Flow;
lstLocations.TextAlign = TextAlign.Right;
lstLocations.CssClass = "CheckBoxList";
if (myReader.HasRows)
{
while (myReader.Read())
{
CheckBox cb = new CheckBox();
cb.ID = myReader[0].ToString();
cb.Text = myReader[1].ToString();
cb.AutoPostBack = false;
cb.CssClass = "CheckBox";
lstLocations.Items.Add(new ListItem(myReader[1].ToString(), myReader[0].ToString()));
lstLocations.Controls.Add(new LiteralControl("<br>"));
}
}
cn.Close();
myReader.Close();
}
And this is my selectedIndexChanged event:
protected void lstLocations_SelectedIndexChanged(object sender, EventArgs e)
{
string value = null;
try
{
foreach (ListItem checkBox in lstLocations.Items)
{
if (checkBox.Selected == true)
{
value = checkBox.Text;
if (value == "Africa")
{
txtCountryOfAfrica.Visible = true;
lblAfricaCountry.Visible = true;
}
}
else
{
value = checkBox.Text;
if (value == "Africa")
{
txtCountryOfAfrica.Visible = false;
lblAfricaCountry.Visible = false;
}
}
}
}
catch (Exception ex)
{
string msg = "Select Error:";
msg += ex.Message;
throw new Exception(msg);
}
}
Page_Load method:
protected void Page_Load(object sender, EventArgs e)
{
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
txtUser.Text = userName;
if (!IsPostBack)
{
ContainerDocumentation.ActiveTab = tabAddCustomer;
PopulateSector();
CreateRegionList();
PopulateOpportunitySource();
CreatelstProductGroupList();
PopulateStatus();
PopulateTenders();
PopulateOtherOpportunityType();
}
}
My guess: you are calling CreateRegionList in Page_Load without checking the IsPostBack property. That reloads all items from database and prevents this event from being triggered.
So check it:
protected bvoid Page_Load(Objject sender, EventArgs e)
{
if(!IsPostBack)
{
CreateRegionList();
}
}
That's because you have to set true to:
lstLocations.AutoPostBack = true;

how to return a datatable if a register number exists

I am trying to display a grid if the user entered register number exists in database, if the register number does not exists this means that I need to display one label also.i am a new one in asp.net,so please help me.
Here is my code below.
public DataTable madhrasaViewByRegNo(string viewByNo)
{
try
{
madhrasaInfo infomadhrasa = new madhrasaInfo();
object decobj = new object();
if (sqlcon.State == ConnectionState.Closed)
{
sqlcon.Open();
}
SqlCommand sqlcmd = new SqlCommand("madhrasaViewByRegNo", sqlcon);
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.Parameters.Add("#regNo", SqlDbType.VarChar).Value = viewByNo;
decobj = sqlcmd.ExecuteNonQuery();
if (decobj == null)
{
decStuId = decimal.Parse(decobj.ToString());
}
else
{
DataTable dtbClass = new DataTable();
SqlDataAdapter sqlda = new SqlDataAdapter("madhrasaViewByRegNo", sqlcon);
sqlda.SelectCommand.CommandType = CommandType.StoredProcedure;
sqlda.SelectCommand.Parameters.Add("#regNo", SqlDbType.VarChar).Value = viewByNo;
sqlda.Fill(dtbClass);
return dtbClass;
}
}
catch (Exception)
{
throw;
}
return null;
}
public void gridfillByNo()
{
madhrasaSp spMadhrasa = new madhrasaSp();
DataTable dtbl = new DataTable();
dtbl = spMadhrasa.madhrasaViewByRegNo(TextBox2.Text);
gvstuResult.DataSource = dtbl;
gvstuResult.DataBind();
}
public void regSearch()
{
madhrasaSp spmadhrasa = new madhrasaSp();
spmadhrasa.madhrasaViewByRegNo(TextBox2.Text);
if (madhrasaSp.decStuId > 0)
{
gridfillByNo();
MultiView1.ActiveViewIndex = 1;
}
else
{
MultiView1.ActiveViewIndex = 0;
Label1.Visible = true;
Label1.Text = "Invalid Register Number";
}
}
protected void Button2_Click(object sender, EventArgs e)
{
regSearch();
}
You Dont you just set the grid view's EmptyDataText to 'Reg No Dosent exist'. It will solve your ploblem.
<asp:GridView ID="GridView1" runat="server" EmptyDataText="register number not available">
</asp:GridView>

Unable to serialize the session state

i am tired wondering the issue for this problem. have read so many blogs and forums for this but i am not able to find out the problem.
I am using "SQLServer" mode to store session.
Everything is working fine. But whenever i use search function in my website, it throws the below error:
"Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode."
I am assuming that this is because of the paging code i have used on that page. That code is as below:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = "select xxxxqueryxxxx";
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
try
{
using (con)
{
con.Open();
da.Fill(ds);
}
}
catch
{
ds = null;
}
finally
{
if (ds != null)
{
CustomPaging page = new CustomPaging();
DataTable dt = ds.Tables[0];
page.PageSize = 10;
page.DataSource = dt;
page.CurrentPageIndex = 0;
no = 1;
Session["DT"] = dt;
Session["page"] = page;
bindData(page, dt);
//set these properties for multi columns in datalist
DataList2.RepeatColumns = 1;
DataList2.RepeatDirection = RepeatDirection.Horizontal;
}
}
}
}
void bindData(CustomPaging page, DataTable dt)
{
try
{
DataList2.DataSource = page.DoPaging;
DataList2.DataBind();
//DataList2.DataSource = SqlDataSource1;
//DataList2.DataBind();
lbtnPre.Enabled = !page.IsFirstPage; //Enable / Disable Navigation Button
// lbtnPre.CssClass = "disabledbtn";
lbtnNext.Enabled = !page.IsLastPage;
//lbtnNext.CssClass = "disabledbtn";
lblStatus.Text = NavigationIndicator(); //Build Navigation Indicator
//for creating page index
DataTable dt1 = new DataTable();
dt1.Columns.Add("PageIndex");
dt1.Columns.Add("PageText");
for (int i = 0; i < page.PageCount; i++)
{
DataRow dr = dt1.NewRow();
dr[0] = i;
dr[1] = i + 1;
dt1.Rows.Add(dr);
}
dlPaging.DataSource = dt1;
dlPaging.DataBind();
dlPaging.RepeatColumns = 10;
dlPaging.RepeatDirection = RepeatDirection.Horizontal;
}
catch (Exception)
{
}
finally
{
page = null;
}
}
string NavigationIndicator()
{
string str = string.Empty; //Page x Of Y
str = Convert.ToString(((CustomPaging)Session["page"]).CurrentPageIndex + 1) + " of " + ((CustomPaging)Session["PAGE"]).PageCount.ToString() + " Page(s) found";
return str;
}
protected void lbtnPre_Click(object sender, EventArgs e)
{
int pageIndex = ((CustomPaging)Session["page"]).CurrentPageIndex;
if (!((CustomPaging)Session["page"]).IsFirstPage)
//Decrements the pageIndex by 1 (Move to Previous page)
((CustomPaging)Session["page"]).CurrentPageIndex -= 1;
else
((CustomPaging)Session["page"]).CurrentPageIndex = pageIndex;
//Binds the DataList with new pageIndex
bindData(((CustomPaging)Session["page"]), ((DataTable)Session["DT"]));
}
protected void lbtnNext_Click(object sender, EventArgs e)
{
int pageIndex = ((CustomPaging)Session["page"]).CurrentPageIndex;
if (!((CustomPaging)Session["page"]).IsLastPage)
//Increments the pageIndex by 1 (Move to Next page)
((CustomPaging)Session["page"]).CurrentPageIndex += 1;
else
((CustomPaging)Session["page"]).CurrentPageIndex = pageIndex;
//Binds the DataList with new pageIndex
bindData(((CustomPaging)Session["page"]), ((DataTable)Session["DT"]));
}
protected void DataList2_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Redirect("Default2.aspx?partnumber=" + DataList2.DataKeyField[DataList2.SelectedIndex].ToString());
}
protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "Select")
{
no = int.Parse(e.CommandArgument.ToString()) + 1;
((CustomPaging)Session["page"]).CurrentPageIndex = int.Parse(e.CommandArgument.ToString());
//Binds the DataList with new pageIndex
bindData(((CustomPaging)Session["page"]), ((DataTable)Session["DT"]));
}
}
protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
{
LinkButton btn = (LinkButton)e.Item.FindControl("lnkbtnPaging");
if (btn.Text == no.ToString())
{
btn.ForeColor = System.Drawing.Color.Maroon;
btn.Font.Underline = false;
}
else
{
btn.ForeColor = System.Drawing.Color.DarkCyan;
btn.Font.Underline = false;
}
}
I just want to know what the problem is in the coding and "how to serialize the session"?
What shold i do to improve the coding?
Any help will be appreciated.
Thank You
I guess your custom paging control is not serializable. This must be the cause of the issue.
Anyway, storing a control in session is not a good idea. Just store the few serializable properties which enable to rebuild the control (PageSize and CurrentPageIndex), or pass them in query string for example.
You could also use ViewState if you can
About storing the DataTable in Session, this might be a really bad idea if you have a lot of data and many connected users.

update cancel on gridview asp.net

I am trying to update a gridview on asp.net using a stored procedure but it always resets to the original values. What am I doing wrong?
edit: all page code added now
protected void page_PreInit(object sender, EventArgs e)
{
MembershipUser UserName;
try
{
if (User.Identity.IsAuthenticated)
{
// Set theme in preInit event
UserName = Membership.GetUser(User.Identity.Name);
Session["UserName"] = UserName;
}
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
protected void Page_Load(object sender, EventArgs e)
{
userLabel.Text = Session["UserName"].ToString();
SqlDataReader myDataReader = default(SqlDataReader);
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_EditRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
}
try
{
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
myDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
// myDataReader.Read();
GridViewED.DataSource = myDataReader;
GridViewED.DataBind();
if (GridViewED.Rows.Count >= 1)
{
GridViewED.Visible = true;
lblMsg.Visible = false;
}
else if (GridViewED.Rows.Count < 1)
{
GridViewED.Visible = false;
lblMsg.Text = "Your search criteria returned no results.";
lblMsg.Visible = true;
}
MyConnection.Close();
}
catch (SqlException SQLexc)
{
Response.Write("Read Failed : " + SQLexc.ToString());
}
}
//to edit grid view
protected void GridViewED_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewED.EditIndex = e.NewEditIndex;
}
protected void GridViewED_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_UpdateRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
command.Parameters.Add("#PostalAddress", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[0].Controls[0]).Text;
command.Parameters.Add("#TelephoneNo", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
command.Parameters.Add("#Website", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
command.Parameters.Add("#Email", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
}
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
command.ExecuteNonQuery();
MyConnection.Close();
GridViewED.EditIndex = -1;
}
I suspect the code loading the grid is being invoked upon postback, which is causing the data to be pulled from the database when you don't want it to.
Yes - I think you want the code to only load if it is not a postback. You can use the Page.IsPostBack property for this.
Something like this:
protected void Page_Load(object sender, EventArgs e)
{
userLabel.Text = Session["UserName"].ToString();
if (!IsPostBack) {
SqlDataReader myDataReader = default(SqlDataReader);
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_EditRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
}
try
{
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
myDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
// myDataReader.Read();
GridViewED.DataSource = myDataReader;
GridViewED.DataBind();
if (GridViewED.Rows.Count >= 1)
{
GridViewED.Visible = true;
lblMsg.Visible = false;
}
else if (GridViewED.Rows.Count < 1)
{
GridViewED.Visible = false;
lblMsg.Text = "Your search criteria returned no results.";
lblMsg.Visible = true;
}
MyConnection.Close();
}
catch (SqlException SQLexc)
{
Response.Write("Read Failed : " + SQLexc.ToString());
}
}
}
Don't bind your data in the Page_Load event. Create a separate method that does it, then in the Page Load, if !IsPostback, call it.
The reason to perform the databinding is it's own method is because you'll need to call it if you're paging through the dataset, deleting, updating, etc, after you perform the task. A call to a method is better than many instances of the same, repetitive, databinding code.

Resources