Total Row Count SqlDataSource GridView - c#

So I have a GridView set up to a SqlDataSource. Paging is enabled and I have a drop down menu that changes the number of rows displayed per page. I am able get the total of rows displayed in a single page but I want to show the total number of rows as well. (Like this: "Showing 1 - 25 of 315").
So, my questions are:
1) How do I get the total number of rows for the entire DataSource? (not just GridView) The code I have, OnSelectedData method, does not work and returns a zero.
2) How do I get the numbers to display differently for each page? For example, on the second page it needs to say "Showing 26 - 50 of 315"
Here's my code (C#):
public partial class UserControls_BloombergAllUsersControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
int gridViewTotalRowCount;
protected void onSelectedData(object sender, SqlDataSourceStatusEventArgs e)
{
gridViewTotalRowCount = e.AffectedRows;
}
protected void GridView1_DataBound(object sender, EventArgs e)
{
int pageRowsCount = GridView1.Rows.Count;
Total1.Text = "Showing 1 - " + pageRowsCount.ToString() + " of " + gridViewTotalRowCount.ToString();
}
private void BindGridView1()
{
try
{
this.GridView1.DataBind();
if (Convert.ToInt32(DropDownList1.SelectedValue) != null)
GridView1.PageSize = Convert.ToInt32(DropDownList1.SelectedValue);
}
catch (Exception ex)
{ throw ex; }
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindGridView1();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
BindGridView1();
}
}
If anyone could help that would be great. Thanks!

you could set paging information to Total1 text in onSelectedData handler as the following
protected void onSelectedData(object sender, SqlDataSourceStatusEventArgs e)
{
int startRowOnPage = (GridView1.PageIndex * GridView1.PageSize) + 1;
int lastRowOnPage = startRowOnPage + GridView1.Rows.Count - 1;
int totalRows = e.AffectedRows;
Total1.Text = "Showing " + startRowOnPage.ToString() +
" - " + lastRowOnPage + " of " + totalRows;
}
So you SQLDataSource should be like this sample:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
OnSelected="onSelectedData"
... >
</asp:SqlDataSource>
And you don't need to do anything for paging information in GridView1_DataBound.
I mean you could remove OnDataBound="GridView1_DataBound" out from your GridView declaration.
EDITED
To set the PageSize, you should set a default value for it such as the following sample:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Convert.ToInt32(DropDownList1.SelectedValue) != null)
GridView1.PageSize = Convert.ToInt32(DropDownList1.SelectedValue);
}
}

Since you are using SqlDataSource, try this code:
Protected Sub SqlDataSource1_Selected(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEvent Args) Handles
SqlDataSource1.Selected
Dim cnt As Integer = e.AffectedRows
End Sub

Related

how to pass session value from button click to another cs file

I am trying to attempt to perform a calculation on a button click on one asp.net form (invoice.aspx) then pass it to another response (print.aspx) form and insert that value into a label. However when ever I click the submit the value ends up being 0. No errors arise when this happens. Can this be done??
The following code I have is:
print.aspx.cs
public partial class print : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DateTime date = DateTime.Now;
lblDateIssue.Text = " Date Issue:" + date.ToShortDateString();
var dueDate = date.AddDays(14);
lblDueDate.Text = " DueDate:" + dueDate.ToShortDateString();
double subTotal1 = (double)(Session["subTotal1"]);
lblItem1Ttl.Text = subTotal1.ToString();
}
}
invoice.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Session["subTotal1"] = 0.0;
}
public void btnSubmit_Click(object sender, EventArgs e)
{
int qty1 = Int32.Parse(txtQty1.Text);
double price1 = double.Parse(txtPrice1.Text);
Session["subTotal1"] = (double)Session["subTotal1"] + (price1 * qty1);
}
}
Any guidance would be appreciated
So rather than using the action attribute in the invoice.aspx form. I removed that attribute and put in Server.Transfer("print.aspx", true); to post to the response page on the button click event. I have also added the try - catch functions to stop the exception throwing. So thanks #dee-see because it was the life cycle just had to go a slightly different way to get around it. The full solution is below
invoice.aspx.cs:
public partial class invoice : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
Session["subTotal1"] = 0.0;
Session["subTotal2"] = 0.0;
Session["subTotal3"] = 0.0;
}
}
public void btnSubmit_Click(object sender, EventArgs e)
{
try
{
int qty1 = Int32.Parse(txtQty1.Text);
double price1 = double.Parse(txtPrice1.Text);
Session["subTotal1"] = (double)Session["subTotal1"] + (price1 * qty1);
}
catch
{
txtQty1.Text = "";
txtPrice1.Text = "";
}
try
{
int qty2 = Int32.Parse(txtQty2.Text);
double price2 = double.Parse(txtPrice2.Text);
Session["subTotal2"] = (double)Session["subTotal2"] + (price2 * qty2);
}
catch
{
}
try
{
int qty3 = Int32.Parse(txtQty3.Text);
double price3 = double.Parse(txtPrice3.Text);
Session["subTotal3"] = (double)Session["subTotal3"] + (price3 * qty3);
}
catch
{
txtQty3.Text = "";
txtPrice3.Text = "";
}
Server.Transfer("print.aspx", true);
}
}
print.aspx.cs:
public partial class print : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DateTime date = DateTime.Now;
lblDateIssue.Text = " Date Issue:" + date.ToShortDateString();
var dueDate = date.AddDays(14);
lblDueDate.Text = " DueDate:" + dueDate.ToShortDateString();
lblItem1Ttl.Text += "$" + (double)(Session["subTotal1"]);
lblItem2Ttl.Text += "$" + (double)(Session["subTotal2"]);
lblItem3Ttl.Text += "$" + (double)(Session["subTotal3"]);
double total = ((double)(Session["subTotal1"]) + ((double)(Session["subTotal2"])) + (double)(Session["subTotal3"]));
lblTotalAmount.Text += "$" + total;
}
}

how to assign value for drop down select item c#

i need to assign value for selected value drop down in aspx for example
dropdownlist items
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
AutoPostBack="True">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
AutoPostBack="True">
<asp:ListItem>a</asp:ListItem>
<asp:ListItem>b</asp:ListItem>
<asp:ListItem>c</asp:ListItem>
</asp:DropDownList>
if user select any item in dropdownlist1 it should increment value 2 then
if user select any item in dropdownlist2 it should increment value 2
i need to display total
i tried this code
static int i = 0;
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
i += 2;
Label1.Text = "hello"+i;
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
i += 2;
Label1.Text = "hello"+i;
}
its working but problem is if user first select 1 in dropdown //i=2 then user select b //i=4 if user again select 1 //i=6. it should not increment if user select any value in particular drop down list. how to do it. any idea....
You're using a static variable so the i value will be kept between postbacks and will be common to all users, this is incorrect.
You need to store it in ViewState, HiddenField, or Session in order to keep the value between postbacks and also keep the value different for each user.
Here's what I would've done using ViewState:
private int Counter
{
get
{
if (ViewState["Counter"] == null)
{
return 0;
}
else
{
return (int)ViewState["Counter"];
}
}
set
{
ViewState["Counter"] = value;
}
}
private bool DropDown1Selected
{
get
{
if (ViewState["DropDown1Selected"] == null)
{
return false;
}
else
{
return (bool)ViewState["DropDown1Selected"];
}
}
set
{
ViewState["DropDown1Selected"] = value;
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (!this.DropDown1Selected)
{
this.DropDown1Selected = true;
this.Counter += 2;
}
Label1.Text = string.Format("hello{0}", this.Counter);
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
this.Counter += 2;
Label1.Text = string.Format("hello{0}", this.Counter);
}
Few of the answers above are talking about static variable getting reset after post back, this is incorrect, Static variables keep their values for the duration of the application domain. It will survive many browser sessions until you restart the web server Asp.net Static Variable Life time Across Refresh and PostBack
That being said, it is definitely not a good idea to use Static variables and instead go with the approaches suggested using Session or Viewstate.
About your question, I guess you want to increment the value only first time a value is chosen from the drop down list, to achieve this you would want to have a flag to let you know if the value is already selected, something on the below lines:
static bool DrpDown1;
static bool DrpDown2;
static int i = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DrpDown1 = false;
DrpDown2 = false;
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (!DrpDown1)
{
i += 2;
Label1.Text = "hello" + i;
DrpDown1 = true;
}
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
if (!DrpDown2)
{
i += 2;
Label1.Text = "hello" + i;
DrpDown2 = true;
}
}
You need a temporary store like ViewState or Session to keep you values and get it back from
there.
private int GetValue()
{
return Int32.Parse(ViewState["temp"]);
}
private void SetValue(int i)
{
if(ViewState["temp"]==null)
{
ViewState["temp"]=i;
}
else
{
ViewState["temp"]= i+Int32.Parse(ViewState["temp"]);
}
}
and use it in your code as follows
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SetValue(2);
Label1.Text = string.Format("hello{0}", GetValue());
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
SetValue(2);
Label1.Text = string.Format("hello{0}", GetValue());
}

Asp.net listview does not display data correctly

My problem is that when i display data in listview for first time then it show correctly but when i display data second time then listview does not update the data correctly. I have made a function for databinding with listview which i have called in pageLoad and some other method.
Can anyone please give me a solution about this ?
I have also uploaded my source code for more detail.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadDataIntoListView();
}
}
protected void LoadDataIntoListView()
{
Users objQuery = new Users();
string adminID = "Here is my query to get the data from MS-SQL";
objQuery.ExecuteSql(str);
if (objQuery.RowCount > 0)
{
Title = "Row affected";
lstAppointments.Items.Clear();
lstAppointments.DataSource = objQuery.DefaultView;
lstAppointments.DataBind();
}
else
{
Title = "None Row affected";
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
string caseID = (string)Session["caseID"];
//string updateQuery = "update Cases set sCaseStatus='cancel' where iCaseID= '" + caseID + "'";
Cases objCases = new Cases();
objCases.LoadByPrimaryKey(Convert.ToInt32(caseID));
if (String.Equals(objCases.SCaseStatus, "cancel"))
{
Page.Title = "No Update";
ModalPopupExtender1.Hide();
}
else
{
objCases.SCaseStatus = "cancel";
objCases.Save();
Page.Title = "No Update";
ModalPopupExtender1.Hide();
lstAppointments.Items.Clear();
LoadDataIntoListView();
}
}
Thanks in advance.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadDataIntoListView();
}
}
You are binding data in not Postback. That means it does not binds data when you postback to same page. If you want to bind that on every page load, call the function LoadDataIntoListView() in Page_Load

Dynamically created LinkButton posts back but does not call onClick Method

My issue is the page posts back but does not call the method.
Here is where I create the link Buttons inside the RenderProducts method
for (var counter = 1; counter <= numberOfPages; counter++)
{
var pagingLink = new LinkButton
{
Text = " " + counter.ToString(CultureInfo.InvariantCulture) + " ",
ID = "page" + counter
};
pagingLink.Attributes["runAt"] = "server";
pagingLink.Attributes["class"] = "paging-link";
pagingLink.Attributes.Add("AutoPostBack", "true");
pagingLink.Attributes.Add("AutoEventWireup", "true");
pagingLink.Click +=ChangePage;
paging.Controls.Add(pagingLink);
}
The method it is calling
public void ChangePage(object sender, EventArgs args)
{
// handle this particular case
RenderProducts(2);
}
For completeness below you will see on PostBack I prevent it's default action
protected void Page_Load(object sender, EventArgs e)
{
GetSideBar();
BuildRefineSearch();
PopulateList();
PerformSearch();
if(!IsPostBack )
{
RenderProducts(1);
}
}
I moved everything to the
override protected void OnInit(EventArgs e)
as this was a user control this solved my issue.
Thanks to Chandermani for getting me to think about when my event was firing.

GridView getting the data trough the id asp.net

The problem really is that i do can trough the selects on the gridview get the data trough the id, but then i use the search option i implemented on the page and the gridview shows the ones it gets that match the result but if i press select it will redirect to the page with the wrong id, isntead of getting the id of the one i selected it gets the id of the field that was on the 1st position of the cell.
Here is the code:
protected void Page_Load(object sender, EventArgs e)
{
TeamGest.DBLayer.DBLTeams dbl = new TeamGest.DBLayer.DBLTeams();
GridView1.DataSource = dbl.List();
GridView1.DataBind();
TeamGest.DBLayer.DBLPlayers dbl1 = new TeamGest.DBLayer.DBLPlayers();
GridView2.DataSource = dbl1.List();
GridView2.DataBind();
}
protected void MyMenu_MenuItemClick(object sender, MenuEventArgs e)
{
{
MyMultiView.ActiveViewIndex = Int32.Parse(e.Item.Value);
int i;
for (i = 0; i <= MyMenu.Items.Count - 1; i++)
{
if (i == Convert.ToInt32(e.Item.Value))
{
MyMenu.Items[i].Text = MyMenu.Items[i].Text;
}
else
{
MyMenu.Items[i].Text = MyMenu.Items[i].Text;
}
}
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
Response.Redirect("DetalhesClube.aspx?Id="+row.Cells[0].Text);
}
protected void Button1_Click1(object sender, EventArgs e)
{
string searchStringTeam = TextBox1.Text;
GetTeamResults(searchStringTeam);
}
protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView2.SelectedRow;
Response.Redirect("DetalhesJogador.aspx?Id=" + row.Cells[0].Text);
}
protected void Button2_Click(object sender, EventArgs e)
{
string searchStringPlayer = TextBox2.Text;
GetPlayerResults(searchStringPlayer);
}
Don't use the cell values. That's what the DataKeys collection is for:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="ID, SomeOtherColumn" ...>
And in code-behind all you need is the row index:
var rowIndex = 0;
var ID = (int)GridView1.Rows[rowIndex]["ID"];

Categories

Resources