C# count listview item entry - asp.net

I want to display ListView row count on how many user, but i only got 0 value.
Example code:
Response.Write("Total User in List: " + ListView1.Items.Count());
Thanks for help.
NOTE: I'm placing it on .cs Page load
Sorry for the raw data,
I didn't insert/add using code i just populate it manually on database

Put your code inside IsPostBack and then try
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ListView1.DataSource = listUsers;
ListView1.DataBind();
Response.Write(ListView1.Items.Count);
}
}

Related

Update the data in database in asp.net

I can successfully select the data I want to update to another page and populate my text boxes but if I set the selected values to my textbox and then try to update it wouldn't work and the same data is shown in database table.
However if I DO NOT set those values to my textboxes, then I can successfully update which is not what I am after.
I would like the user to see the data and record that s being updated
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
UserClassesDataContext db= new UserClassesDataContext();
var qr = from user in db.Users
where user.user_id == new Guid(Request.QueryString["user_id"])
select user;
foreach (var q in qr)
{
TextBox1.Text = q.user_name;
TextBox2.Text = q.password;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
UserClassesDataContext db = new UserClassesDataContext();
var qr = from user in db.Users
where user.user_id == new Guid(Request.QueryString["user_id"])
select user;
foreach (var q in qr)
{
q.user_name = TextBox1.Text;
q.password = TextBox2.Text;
}
db.SubmitChanges();
Response.Redirect("Default.aspx");
}
What am I doing wrong?
Thanks
The problem is, when you submit the button, the code inside Page_Load event is executing again.That means it is reading the data from your table and setting the value to textboxes(thus overwriting what user updated via the form ) and you are updating your record with this values (original values). So basically you are updating the rows with same values.
You can use the Page.IsPostBack property to determine whether the event is occurred by a postback(button click) or initial page load.
This should fix it.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
// to do: read and set to textbox here.
}
}

How to Display ASP Gridiew Empty Data Text after Clicking Search Button

Pls Help Me
The problem here is that i want the empty data template to be Display after the button search has been click but right now every time i open the page, it will show the empty data template before do any searching ....
if(!IsPostBack)
{
//put ur gridview connection here;
}
protected void Page_Load(object sender, EventArgs e)
{
grid1.DataSource = sqlboxfile;
DataBind();
grid2.Visible = false;
}

Select all items in listbox when updated via UpdatePanel

protected void Page_Load(object sender, EventArgs e)
{
if (ScriptManager.GetCurrent(this).IsInAsyncPostBack)
{
string id = ScriptManager.GetCurrent(Page).AsyncPostBackSourceElementID;
if (id == cboGroup.UniqueID)
{
foreach (ListItem i in lstTest.Items)
i.Selected = true;
}
}
}
This code runs when my cboGroup causes my UpdatePanel to refresh which has the lstTest in it and the data inside of it gets updated, but it does NOT select them all. How can I make it so when my UpdatePanel is finished refreshing all elements of the list box that it refreshed get selected?
[edit] I'm noticing now that at this point what's in the listbox is the previous values and not the new values I would need. So this seems to be before the listbox is filled with data (which is via a SqlDataSource) so it's probably overwriting this.
I was able to put my selection code in the list box's DataBound() event.
protected void lstTest_DataBound(object sender, EventArgs e)
{
SelectAllTest();
}

When to fill a sorted asp:GridView?

i've tried to ask this question a number of ways. It's a difficult question to answer because you have to understand what's going on.
When do i fill a GridView?
The nieve answer is during Page_Load, if not a PostBack:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds = GetStuffToShow();
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
The problem with that is that if it is a postback, the grid is not filled. The reason the grid is not filled is because we've turned off the viewstate of the grid.
So don't look at IsPostBack
We need to always fill the grid, postback or not:
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds = GetStuffToShow();
GridView1.DataSource = ds;
GridView1.DataBind();
}
The problem with that is that if the user sorts a column, the OnSorting event is called after both Page_Init and Page_Load:
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataSet ds = GetStuffToShow(e.SortExpression, e.SortDirection);
GridView1.DataSource = ds;
GridView1.DataBind();
}
we've run two database queries, when only one was required.
Cache is fine for column sorting
If i'm willing to accept invalid cache during column sorting, i can store the DataSet in the session variable, as long as i invalidate it for any other operation.
The problem is the OnSorting event is called after i need it (Page_Load):
protected void Page_Load(object sender, EventArgs e)
{
if (AGridViewOnSortingEventIsntBeingRaised)
{
DataSet ds = GetStuffToShow();
StoreTheDatasetInTheSessionSomehowInCaseTheyCallSortInTheFuture(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataSet ds = GetDataSetOutOfSessionSomehowThatDamnWellBetterBeThere();
SomehowSortAReadOnlyDisconnectedDataSet(ds, e.SortExpression, e.SortDirection);
GridView1.DataSource = ds;
GridView1.DataBind();
}
Fear of the unknown
Then there's still the terror i have because i turned off viewstate of the GridView. i don't think that a read-only asp:GridView should need tens of kilobytes base64 encoded, when i can just rebuild it from the server (or from memory).
But i believe that i am obligated to return the GridView to the state it was in the last time the page was rendered. And i have to do it before Page_Load (i.e. during Page_Init). i have this fear because someone said so. So i turn it into
protected void Page_Init(object sender, EventArgs e)
{
if (AGridViewOnSortingEventIsntBeingRaised)
{
DataSet ds = GetStuffToShow();
StoreTheDatasetInTheSessionSomehowInCaseTheyCallSortInTheFuture(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
The problem with this is that GetStuffToShow depends on things the user has typed into text boxes, which don't exist during Page_Init
Anyway, i'm rambling. It's too hot in here. Hopefully this question will be answered, unlike my other recent frustrations with asp.net
Bonus Reading
Sorting GridView Formed With Data Set
By adding a couple of hidden fields, one for the sort expression, and the other for the sort direction you can use those values to populate the GridView once at page load and then update the sorting in the Sorting event (sort code modified from the All-In-One Code Framework GridView sample):
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds = GetStuffToShow();
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
// If the sorting column is the same as the previous one,
// then change the sort order.
if (SortExpression.Value.Equals(e.SortExpression))
{
SortDirection.Value = SortDirection.Value.Equals("ASC") ? "DESC" : "ASC";
}
// If sorting column is another column,
// then specify the sort order to "Ascending".
else
{
SortExpression.Value = e.SortExpression;
SortDirection.Value = "ASC";
}
var sortedView = new DataView(<convert your DataSet to a DataTable>)
{ Sort = string.Format("{0} {1}", this.SortExpression.Value, this.SortDirection.Value) };
GridView1.DataSource = sortedView;
GridView1.DataBind();
}
Note that SortDirection and SortExpression are the hidden fields. This also lends itself well to caching the DataSet.
Also, I wouldn't be concerned about the Page_Init issue that you brought up. That should only apply if you are dynamically creating your Controls.
A simple solution is to call Gridview.DataBind() on the Page.Pre_Render event, which makes it called after having handled any Button/Sorting, events. This a good way to ensure you call it only once per Request.
To make things clearer, it is also a good thing to access your dataset through a Property which will basically call your "Store-The-Dataset-In-The-Session-Somehow-In-Case-They-Call-Sort-In-The-Future" method in its Set part and your "Get-Data-Set-Out-Of-Session-That-Had-Better-Be-There" in the Get part.
You may try to fill the grid on Gridview Needdatasource event
it will be called when ever you perform a postback and get the proper functionality what ever you code in the event.
also if you want to bind it again you can just data databind method and that will call the needdatasource event again

Get the row that has been clicked in the gridview

I have added OnClick event dynamically for gridview.So when I click on any of the row on grid view, the event is fired but I can't get which row is clicked.
This is the code where I add event.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Attributes["OnClick"] = Page.ClientScript.GetPostBackClientHyperlink(btnGrid, string.Empty);
}
//This is the code which catches this event
protected void GridView1_OnClick(object sender, EventArgs e)
{
_ID="10" //Static data. I need this from the gridview1.row[ClickedRow].cell[0]
}
I fear you'll have to "manually" assign this value.
For this, add hidden input element to the form:
<input type="hidden" name="clicked_row" />
Change the code to:
e.Row.Attributes["OnClick"] = Page.ClientScript.GetPostBackClientHyperlink(btnGrid, string.Empty) + "; document.forms[0].elements['clicked_row'].value = '" + e.Row.RowIndex + "';";
And finally, read the index from the Request in the GridView1_OnClick method:
_ID = Int32.Parse(Request.Form["clicked_row"]);
If each row has its own ID change e.Row.RowIndex to e.Row.Id.
I think, you could pass your id/rowindex as parameter to GetPostBackClientHyperlink() and implement the IPostBackEventHandler-interface in your page. The RaisePostBackEvent() method will get the id as input parameter passed in.
I haven't tested this, I just took a look at the example in MSDN documentation
Try passing in the row instead of the grid, like this:
e.Row.Attributes["OnClick"] = Page.ClientScript.GetPostBackClientHyperlink(e.Row, String.Empty);
And in your event handler:
protected void GridView1_OnClick(object sender, EventArgs e)
{
if (sender is GridViewRow)
{
int index = ((GridViewRow)sender).RowIndex;
}
}
I'm not positive, but I think the GridView OnClick will still fire since you're passing a child element of the grid.

Resources