GridView ASP.NET Sorting - asp.net

I have an ASP.NET GridView that just won't sort! I'm sure that I am missing something pretty obvious.
Page.aspx
<asp:GridView ID="TimeAwayGridView" runat="server" AutoGenerateSelectButton="False"
AutoGenerateEditButton="False" AutoGenerateDeleteButton="False" AllowPaging="False"
AllowSorting="True" CssClass="gridview" OnSorting="TimeAwayGridView_Sorting">
<Columns>
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:BoundField DataField="Hours" HeaderText="Hours" SortExpression="Hours" />
</Columns>
<EmptyDataTemplate>
There are currently no items in this table.
</EmptyDataTemplate>
</asp:GridView>
Page.aspx.cs
protected void TimeAwayGridView_Sorting(object sender, GridViewSortEventArgs e)
{
}

Asp.Net Datagrip provides you with sorting event, and name of the column that was clicked in GridViewSortEventArgs, but you have to provide you own sort implementation in TimeAwayGridView_Sorting function. Meaning you should sort your datasource and rebind the datagrid.

Related

How to delete a row in a dynamically generating grid view?

Hello Respected sirs,
I am generating a shopping cart like ordering system, in which i add/bind the productname, productprice, and productquantity from DataTable to GridView.
I have Added an ImageButton to the gridview only for deleting the selected row.
I also know that we can not delete a row from a dynamically generated grid view. so i placed a code in the ImageButton Click event that deletes the row from DataTable (Which is STATIC during the whole process) and again binds the Data With GridView.
Please note that i hv already once bind the data with gridview in my "BTN_ADD TO CART_Clicked".
Here is my code snippet,
protected void gvorderlist_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int index = Convert.ToInt32(e.CommandArgument);
DataRow row = dt.Rows[index];
dt.Rows.Remove(row);
gvorderlist.DataSource = dt;
gvorderlist.DataBind();
}
}
and ASP code is,
<asp:GridView ID="gvorderlist" runat="server" CellPadding="4"
ForeColor="#333333" GridLines="None" AllowPaging="True" PageSize="5"
onpageindexchanging="gvorderlist_PageIndexChanging"
onrowcommand="gvorderlist_RowCommand">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Cancel Order" ShowHeader="False">
<ItemTemplate>
<asp:ImageButton ID="ImgbtnCancelOrder" runat="server" CausesValidation="false"
ImageUrl="~/images/cross.PNG" OnClientClick="Javascript: return confirm('Aap Chutiye hai');" CommandName="Delete"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I am getting an Error which says : The GridView 'gvorderlist' fired event RowDeleting which wasn't handled.
Any help will be appreciated...
Thank You
The error explains everything. You need todefine the event method for OnRowDeleting in markup:
<asp:GridView ID="gvorderlist" runat="server" CellPadding="4"
ForeColor="#333333" GridLines="None" AllowPaging="True" PageSize="5"
onpageindexchanging="gvorderlist_PageIndexChanging"
onrowcommand="gvorderlist_RowCommand" OnRowDeleting="gvorderlist_RowDeleting">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Cancel Order" ShowHeader="False">
<ItemTemplate>
<asp:ImageButton ID="ImgbtnCancelOrder" runat="server" CausesValidation="false"
ImageUrl="~/images/cross.PNG" OnClientClick="Javascript: return confirm('Aap Chutiye hai');" CommandName="Delete"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And add an empty method in the code:
protected void gvorderlist_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
// No need to implement code here
}
The attributes for the GridView are case-sensitive, so change onrowcommand to OnRowCommand and see if that fires when you click the delete button. If not, you'll need to define OnRowDeleting explicitly. (Also change the capitalization of onpageindexingchange)
Give Command Name=D instead of Delete. It searches for Row_Deleting event when Command Name =Delete.

How to get the Textbox value from DataGridView?

So here I'm trying to get the Textbox filled with the selected data from the DataGridView, so when I clicked the button in the DataGridView, the selected result will be put into the Textbox, I've tried the solution from other resource but still no luck. Can somebody help? Here's the DataGridView code:
DataGridView:
<asp:Panel ID="PanelDGV" runat="server" ScrollBars="None" Height="250" Width="515">
<asp:GridView ID="DGV" runat="server" AutoGenerateColumns="False" GridLines="None" AllowPaging="true" PageSize="8" CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt">
<Columns>
<asp:BoundField DataField="ProjectCode" HeaderText="Project Code" />
<asp:BoundField DataField="ProjectName" HeaderText="Project Name" />
<asp:ButtonField ButtonType="Image" ImageUrl="../Support/Image/Edit.png" ItemStyle-HorizontalAlign="Center" CommandName="CmdSearch" HeaderText="Edit">
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:ButtonField>
</Columns>
<PagerStyle CssClass="pgr"></PagerStyle>
AlternatingRowStyle CssClass="alt"></AlternatingRowStyle>
</asp:GridView>
</asp:Panel>
notice the button is:
<asp:ButtonField ButtonType="Image" ImageUrl="../Support/Image/Edit.png" ItemStyle-HorizontalAlign="Center" CommandName="CmdSearch" HeaderText="Edit">
oh, and the textbox's ID is "TbProjectCode", and both are in separate pages, say that 1.aspx contain the textbox and a button to open the datagridview and 2.aspx contain the datagridview and the button to select the Project Code.
thank you
Add OnRowCommand event on your gridview: OnRowCommand="DGV_OnRowCommand".
Then add this on your code behind:
protected void DGV_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "CmdSearch")
{
int index = (int)e.CommandArgument;
GridViewRow row = DGV.Rows[index];
// Get the text on first cell of the row which is the project code.
TbProjectCode.Text = row.Cells[0].Text;
}
}

C# How do I create a Hyperlink OnClick event on GridView?

I'm having trouble creating the GridView I want.
I would like the user to get inside the website and see the GridView which is attached to a DB.
Columns are: ID, InsertionTime, Filepath, ProccessedByUser
Now I want the user to click the filepath he/she would like to process. When he/she clicks the filepath, I want their username (logged in with built-in asp website authentication) to be updated (added) into DB.
My markup is standard and I haven't got to manage with code behind.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" DataSourceID="AccessDataSource1"
onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="starttime" HeaderText="starttime"
SortExpression="starttime" />
<asp:HyperLinkField DataNavigateUrlFields="path" DataTextField="path"
HeaderText="path" />
<asp:BoundField DataField="user" HeaderText="user" SortExpression="user" />
</Columns>
</asp:GridView>
I tried using HyperlinkField but it doesn't seem to support onlick events.
Any suggestions?
Thanks.
I assume you are looking for the LinkButton control which has an OnClick event.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" DataSourceID="AccessDataSource1"
onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="starttime" HeaderText="starttime"
SortExpression="starttime" />
<asp:TemplateField HeaderText="Path" SortExpression="Filepath">
<ItemTemplate>
<asp:LinkButton ID="LbPath" runat="server"
Text='<%# Eval("Filepath") %>'
CommandName="PathUpdate"
CommandArgument='<%#Bind("path") %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="user" HeaderText="user" SortExpression="user" />
</Columns>
</asp:GridView>
Now you can handle the LinkButton's click event or the GridView's RowCommand event.
protected void Gridview1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "PathUpdate")
{
string path= e.CommandArgument.ToString();
// do you what you need to do
}
}
Note that i've used a TemplateField which is the most dynamic column type in a GridView since you can add anything you want, even nested GridViews or UserControls.
You could use a ButtonField, and then handle OnRowCommand of the gridview. Example here:
http://msdn.microsoft.com/SV-SE/library/system.web.ui.webcontrols.buttonfieldbase.buttontype.aspx
You can set the ButtonType attribute of ButtonField to display the button as a Link.

ASP.net commandname won't fire

I am having trouble when trying to fire a button in a GridView with the parameter CommandName = "x", I try to reach my "If" in the GridView1_RowCommand event but I just cant for some reason, if you could help me I'd be gratefull .
This is my .aspx part
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" CellPadding="4"
EnableModelValidation="True" ForeColor="#333333" GridLines="None"
Height="193px" Width="968px" AllowPaging="True" AllowSorting="True"
AutoGenerateColumns="False" DataKeyNames="ID"
DataSourceID="SOURCE1" onrowcommand="GridView1_RowCommand">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button Text = "Seleccionar" runat="server" CommandName="X" CommandArgument='<%# Container.DataItemIndex %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="IDEmpresa" HeaderText="IDEmpresa"
SortExpression="IDEmpresa" />
</Columns>
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
And this is my C# code:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "X")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
Label1.Text = "WOW It reached out";
}
}
I followed the instructions of the ASP.net page, and im fairly new to .net (I dont know if the UpdatePanel has something to do with it)
Doing a quick test, the code you have provided works, but I did have to wire up my own datasource.
What you are missing here is that Label1 is outside of your UpdatePanel and will not refresh based on your localized postback within the UpdatePanel.
A word of caution with GridViews and UpdatePanels/Buttons. Make sure you are not manually binding/rebinding during Page_Load, and if you have code to do so, you do so within an if(!IsPostBack) { } statement.

Access Cell value in gridview

I thought this would be an easy one for me to figure out (or atl east find someone online who has) but I am running into issues.
I have the following code that creates my gridview:
<asp:GridView runat="server" ID="ContactsGrid" AutoGenerateColumns="False" DataSourceID="LinqContact"
CellPadding="4" ForeColor="#333333" GridLines="None" OnRowDeleting="ContactsGridView_RowDeleting" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="IConact_ID" Visible="false" ReadOnly="true" />
<asp:BoundField DataField="cFirstName" HeaderText="First Name" ReadOnly="True" />
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" />
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="LinqContact" runat="server" ContextTypeName="TIPS.App_Data.TIPSDataContext" onselecting="LinqContact_Selecting" >
</asp:LinqDataSource>
Now on the c# side, I want to be able to pull the value from the first column (which is hidden) and use it to delete that specific record (with the onroedeleting event), but all the ways I found to pull the value, all come up null, like what would happen if I didn't have a LinqDatasource.
I have tried (and a slew of other that really didn't seem to be right, so not listed):
ContactsGrid.SelectedRow.Cells[0].Text;
ContactsGrid.Columns[0];
Thanks for any help!
Edit:
Ok, so I found that you can't get the value of a column this is hidden when you hide it using the grid. I did find a work around. If you hide the column using css instead, you can still access the colum.
<style type="text/css">
.hiddencol
{
display:none;
}
</style>
<asp:BoundField DataField="IContact_ID" ReadOnly="true" itemstyle-cssclass="hiddencol" />
I don't think that this is the prefered .net way. I found a reference to something called datakeynames which seems to be the proper way. I am going to dig into those next.
Edit #2:
I see that Maras and myself both came up with a solution for the hidden field, but I think I found the best one (cause its simple and built in).
In the gridview tag you can set the datakeynames attribute to your column (like a primary key, which is what I was storing in my hidden column) you can also store multiple columns.
<asp:GridView runat="server" ID="ContactsGrid" AutoGenerateColumns="False" DataSourceID="LinqContact" DataKeyNames="IContact_ID"
CellPadding="4" ForeColor="#333333" GridLines="None" OnRowDeleting="ContactsGridView_RowDeleting" >
you can then reference it with:
ContactsGrid.DataKeys[e.RowIndex].Value;
Try this:
void ContactsGrid_RowDeleting(Object sender, GridViewDeleteEventArgs e)
{
ContactsGrid.Rows[e.RowIndex].Cells[0];
}
See here for more details http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdeleting.aspx#Y200
.
Edit after author's comment:
If you set it visibility to 'false' then there is nothing your browser can send you back in postback. You can use hidden field like in the second example:
<asp:GridView runat="server" ID="gv" OnRowDeleting="gv_RowDeleting" AutoGenerateColumns="false" AutoGenerateDeleteButton="true">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="hf" runat="server" Value="<%# ((YourItemType)Container.DataItem).Id %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void gv_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
HiddenField hf = (HiddenField) gv.Rows[e.RowIndex].Cells[0].FindControl("hf");
}

Resources