Gridview.Sort doesn't sort anything? - c#

I'm loading a gridview like so:
protected void Page_Load(object sender, EventArgs e)
{
PopulateAll();
}
private void PopulateAll()
{
DataTable dt = GetSqlTableAsDataTable(_query);
gv_priorities.DataSource = dt;
gv_priorities.Sort("MyColumnHeader", System.Web.UI.WebControls.SortDirection.Ascending);
gv_priorities.DataBind();
}
The sort event is processed, it will fire the OnSorting and OnSorted event if I include them, but why doesn't it actually sort the data? I understand I can sort in the datatable, but why does GridView.Sort() not work?
My gridview has a simple setup:
<asp:GridView runat="server"
ID="gv_priorities"
AllowSorting="true"
OnSorted="gv_priorities_Sorted"
OnSorting="gv_priorities_Sorting"
AllowPaging="true"
PageSize="20"
OnPageIndexChanging="gv_priorities_PageIndexChanging">
<PagerStyle CssClass="PagerStyle" />
</asp:GridView>

Related

How to fill up a GridView with foreach loop

I have this GridView markup:
<asp:GridView ID="GridView1" runat="server" Width ="300px">
<Columns>
<asp:BoundField AccessibleHeaderText="TEXT" HeaderText="TEXT" />
</Columns>
</asp:GridView>
I want to fill up Gridview with some strings through foreach loop:
foreach (GridViewRow row in GridView1.Rows)
{
string f = "this is looping";
row.Cells[0].Text += f;
}
The problem is GridView1 doesn`t display anything...
Well, you can say have a gv like this:
<asp:GridView ID="GridView1" runat="server" CssClass="table" Width="20%">
</asp:GridView>
And then code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
List<string> MyList = new List<string> { "One", "Two", "Three" };
GridView1.DataSource = MyList;
GridView1.DataBind();
}
And we get this:
Or, we can add a listitem (often used for a drop down list, or say listbox).
Thus:
<asp:GridView ID="GridView1" runat="server" CssClass="table"
Width="20%" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="My header"
DataField="Text"/>
</Columns>
</asp:GridView>
(note how we turned off autogen colums)
code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
List<ListItem> MyList = new List<ListItem>();
MyList.Add(new ListItem("One"));
MyList.Add(new ListItem("Two"));
MyList.Add(new ListItem("Three"));
GridView1.DataSource = MyList;
GridView1.DataBind();
}
And we now have this:
So, you can use a simple string list, or even a list item. You loop adding to the object, and THEN feed to the gv.
so, you can loop and build up something, but that thing is THEN bound to the gv.
You can't use foreach loop becouse your GridView doesn't have data source.
Set ObservableCollection as Source, and Add data to collection.

First Click on ASP.NET control does not fire on click event

I'm seeing this behavior on two of my pages, but I'm just going to ask about the one that's more important to me at the moment. I have a page that loads information from a database into a ASP gridview and then allows the user to add a detail to each populated line.
The issue I'm having is that when the 'Edit' button of the gridview and then subsequently the 'Update' or 'Cancel' button, it takes two click to actually fire the onclick event. A post back does take place on the first click, but nothing actually happens.
I'm including the code that seems relevant below. The page uses a master page and there are a number of divs involved with formatting, I'm excluding those.
Gridview and related controls:
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label Text="Plant Selector: " runat="server" />
<asp:DropDownList ID="ddlPlant" OnSelectedIndexChanged="ddlPlant_SelectedIndexChanged" runat="server" />
<asp:Button ID="btnUpdate" Text="Update" OnClick="btnUpdate_Click" runat="server" />
<p />
<asp:Label ID="lblTest" Text="" runat="server" />
<asp:Label ID="lblerror" Text="" ForeColor="Red" runat="server" />
<asp:GridView ID="gridview1" AutoGenerateColumns="false" runat="server" OnRowEditing="gridview1_RowEditing" OnRowCancelingEdit="gridview1_RowCancelingEdit" OnRowUpdating="gridview1_RowUpdating">
<Columns>
<asp:BoundField DataField="JobNum" HeaderText="Job Number" ReadOnly="true" />
<asp:BoundField DataField="ModelNum" HeaderText="Model" ReadOnly="true" />
<asp:BoundField DataField="Customer" HeaderText="Customer" ReadOnly="true" />
<asp:BoundField DataField="SchCompDate" HeaderText="Sch Comp Date" ReadOnly="true" />
<asp:TemplateField HeaderText="Details">
<EditItemTemplate>
<asp:TextBox ID="Txt" Width="98%" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label Text="Click Edit to add details of exception." runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="true" />
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="gridview1" />
</Triggers>
</asp:UpdatePanel>
Sample image below:
Here is the code behind:
private string Plant { get; set; }
// This sets the default plant based off IP.
protected void Page_PreInit(Object sender, EventArgs e)
{
getPlantFromIP();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
populateDDL();
BindData();
}
else
{
Plant = ddlPlant.SelectedValue.ToString();
}
}
// Populates the drop down.
private void populateDDL()
{
ddlPlant.Items.Add("NC");
ddlPlant.Items.Add("WA");
setPlantInDDL();
}
private void setPlantInDDL()
{
if(Plant == "WA")
{
ddlPlant.SelectedIndex = 1;
}
if (Plant == "NC")
{
ddlPlant.SelectedIndex = 0;
}
}
private void getPlantFromIP()
{
if (Request.ServerVariables["REMOTE_ADDR"] == "70.103.118.100")
{
Plant = "WA";
//ddlPlant.SelectedIndex = 1;
}
else
{
Plant = "NC";
//ddlPlant.SelectedIndex = 0;
}
}
// Database Query.
private DataTable getDataFromDatabase()
{
DataTable rTable = new DataTable();
string plant = ddlPlant.SelectedValue.ToString();
using (var conn = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["workorderConnectionString"].ConnectionString))
{
conn.Open();
using (var cmd = conn.CreateCommand())
{
try
{
cmd.CommandText = #"SELECT * FROM reportdatatables.compliance_exception_report
WHERE ExceptionNoted = '0' AND Plant = #plant";
cmd.Parameters.AddWithValue("#plant", plant);
MySqlDataReader reader = cmd.ExecuteReader();
rTable.Load(reader);
reader.Close();
cmd.Dispose();
}
catch
{
}
finally
{
conn.Close();
}
}
}
return rTable;
}
// Binds the data from the database to the gridview.
private void BindData()
{
DataTable data = getDataFromDatabase().Copy();
gridview1.DataSource = data;
gridview1.DataBind();
}
protected void ddlPlant_SelectedIndexChanged(object sender, EventArgs e)
{
//Plant = ddlPlant.SelectedValue.ToString();
BindData();
}
// On edit call.
protected void gridview1_RowEditing(object sender, GridViewEditEventArgs e)
{
}
// On cancel call.
protected void gridview1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gridview1.EditIndex = -1;
}
protected void gridview1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
BindData();
}
Here's what I've tried:
-A lot of posts a read saw this behavior relating to autopostback settings of controls. As you can see I'm made sure to not have any control with the autopostback set to true.
-I had some concern that the behavior might be related to the updatepanel, but removing it doesn't change the behavior at all.
-I read that having AutoEventWireup="true" in your page tag can cause this. I DO have that in my page tag, but setting it to false does not fix the issue and prevents my dropdown from being populated on page load.
-There was another post that suggested the ID of the control could be changing between page load and post back. I monitored the IDs of those controls and I do not see any change in their ID.
So all that being said, I'm hoping someone has a clue as to what I'm missing. If there is any more information I can provide that might help, please let me know.
Thank you in advance.
Try this, which will make the grid editable
protected void gridview1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
for cancel also
protected void gridview1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gridview1.EditIndex = -1;
BindData();
}

How do I get the paging event working?

When I click on the page numbers nothing happens. I have my gridview in a user control.
The breakpoint does not even work.
Is there something that I am missing?
Here is my gridview html:
<asp:GridView ID="grdData" runat="server" AutoGenerateColumns="false"
EmptyDataText="No records" GridLines="none" Width="100%" PageSize="1" AllowPaging="True"
OnPageIndexChanging="grdData_PageIndexChanging" OnSelectedIndexChanged="grdData_SelectedIndexChanged" > <Columns> </Columns>
<HeaderStyle CssClass="titleRow" /> <RowStyle CssClass="itemRow" /> </asp:GridView>
Here is my code behind:
public void grdData_PageIndexChanging(object sender, GridViewPageEventArgs e)
{// actions here }
Try This
public void FillGrid()
{
//here your grid view binding code
}
public void grdData_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdData.PageIndex=e.NewPageIndex;
FillGrid();
}
Since you're saying the break point is "not working" which, I'm assuming, means the compiler is not hitting the breakpoint, you can probably try cleaning the solution and rebuilding after closing all open instances of the browser which has this page opened.
Other way is to explicitly try wiring the event to the event handler in your page_load like
grdData.PageIndexChanging += new EventHandler(grdData_PageIndexChanging);
Hope this helps.

Selecting row of DataGridView?

How do i have the whole row of a data grid view. I have no idea where to start. I have tried this, but has NO idea where to PUT it. :
dataGrid.Rows[index].Selected = true;
I am just looking for a peice of code that will help me! Thanks
It seems you want to do something like this:
protected void Page_Load(object sender, EventArgs e)
{
this.FillGrid();
}
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
this.GridView1.SelectedIndex = e.NewSelectedIndex;
this.FillGrid();
}
private void FillGrid()
{
this.GridView1.DataSource = new[] { "Hello", "World" };
this.GridView1.DataBind();
}
And in the aspx file:
<asp:GridView ID="GridView1" runat="server"
onselectedindexchanging="GridView1_SelectedIndexChanging">
<Columns>
<asp:CommandField ShowSelectButton="True" />
</Columns>
<SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
</asp:GridView>
Which produces this output:

How to enable Paging and Sorting on ASP.NET 4.0 GridView programmatically?

I am using ASP.NET 4.0 with C# (Visual Web Developer 2010 Express).
I have successfully managed to implement a simple GridView bound to a stored procedure data source using declarative ASP.NET code as shown here:
<asp:GridView
ID="grdTrades"
runat="server"
DataKeyNames="tradeId"
EnablePersistedSelection="true"
SelectedRowStyle-BackColor="Yellow"
AllowPaging="true"
AllowSorting="true"
PageSize = "20"
AutoGenerateColumns="false"
DataSourceID="sdsTrades"
>
<Columns>
<asp:CommandField ShowSelectButton="true" ButtonType="Link" SelectText="Select" />
<asp:BoundField DataField="tradeId" HeaderText="TradeId" ReadOnly="True" SortExpression="tradeId" />
< ... more columns ... >
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sdsTrades" runat="server"
ConnectionString="<%$ ConnectionStrings:TradesDB %>"
ProviderName="<%$ ConnectionStrings:Trades.ProviderName %>"
SelectCommand="usp_GetTrades" SelectCommandType="StoredProcedure">
</asp:SqlDataSource>
It works great including paging and sorting. I want to remove the SqlDataSource and use code-behind (I'm trying to put database access code in one place). So far I have this in my code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
grdTrades.SelectedIndex = 0;
DBUtil DB = new DBUtil();
grdTrades.DataSource = DB.GetTrades();
grdTrades.DataKeyNames = new string[] { "tradeId" };
grdTrades.DataBind();
}
}
// this is needed otherwise I get "The GridView 'grdTrades' fired event PageIndexChanging which wasn't handled."
void grdTrades_PageIndexChanging(Object sender, GridViewPageEventArgs e)
{
grdTrades.PageIndex = e.NewPageIndex;
grdTrades.DataBind();
}
My declarative code now looks like:
<asp:GridView
ID="grdTrades"
runat="server"
EnablePersistedSelection="true"
SelectedRowStyle-BackColor="Yellow"
AllowPaging="true"
AllowSorting="true"
PageSize = "20"
AutoGenerateColumns="false"
OnPageIndexChanging="grdTrades_PageIndexChanging"
>
<Columns>
<asp:CommandField ShowSelectButton="true" ButtonType="Link" SelectText="Select" />
<asp:BoundField DataField="tradeId" HeaderText="TradeId" ReadOnly="True" SortExpression="tradeId" />
< ... more columns ... >
</Columns>
</asp:GridView>
The problem is when I click on a page number the page becomes blank. I would also like to implement sorting but would like to get the paging working first. Please help.
Thanks
You need to bind your GridView every time you change page.
For example:
void grdTrades_PageIndexChanging(Object sender, GridViewPageEventArgs e)
{
grdTrades.DataSource = DB.GetTrades();
grdTrades.PageIndex = e.NewPageIndex;
grdTrades.DataBind();
}
My advice would be to store your results from DB.GetTrades() in the ViewState (or Cache) so you don't need to go to the database everytime you change page.
Sorting can become quite difficult when doing this, though.
You can always use an ObjectDataSource instead of a SqlDatasource. You can then point your ObjectDataSource to look at your DB.GetTrades() function. Sorting and Paging will work automatically.
Hope that helps.
You can create a method to for binding the grid view instead of Binding it again in Paging. By creating a method that binds the Grid View you can always call the method to Bind the grid view whenever you want.
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BindgrdTrades();
}
private void BindgrdTrades()
{
DBUtil DB = new DBUtil();
grdTrades.DataSource = DB.GetTrades();
grdTrades.DataKeyNames = new string[] { "tradeId" };
grdTrades.DataBind();
}
}
void grdTrades_PageIndexChanging(Object sender, GridViewPageEventArgs e)
{
grdTrades.PageIndex = e.NewPageIndex;
BindgrdTrades();
}
}
I had to make my _PageIndexChanging counter to public (I'm so new at asp.net that I have no idea why it matters). The page would through an error saying it couldn't find the class. These posts were a great help to get paging working with otherwise near verbatim logic. Thanks to all the posters for taking the time to lay it out so clearly. Here's the code I ended up with:
public partial class Requests : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BindgrdBuilds();
}
}
private void BindgrdBuilds()
{
// Link GridView to datasource
GridView1.DataSource = BuildData.getBuilddata();
// Bind SQLDataSource to GridView after retrieving the records.
GridView1.DataBind();
}
public void GridView1_PageIndexChanging(Object sender, GridViewPageEventArgs e)
{
// increment PageIndex
GridView1.PageIndex = e.NewPageIndex;
// bind table again
BindgrdBuilds();
}
}
I stuck with AutoGenerated columns, and I'm doing some row binding to my data on the cs page that I didn't include above, but here's my asp code for the GridView:
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<asp:GridView ID="GridView1"
OnRowDataBound="GridView1_RowDataBound"
OnPageIndexChanging="GridView1_PageIndexChanging"
runat="server"
SelectedRowStyle-BackColor="Yellow"
AllowPaging="true"
AllowSorting="true"
PageSize = "20"
AutoGenerateColumns="true"
<-- table formatting code trimmed -->
</asp:GridView>
I hope someone else can make use of this info, this thread was a great, simple example to follow. Now that paging works it's time to get real fancy and come up with a new name for GridView1 :D

Categories

Resources