I'm having trouble getting a gridview's button column to do anything. I'm using a DirectoryInfo object to get the details of a file. I put the filename and the date created into the gridview columns. The third column is a button column. I have set the datakeys(Name, CreationTime), named the button column's commandName to "sendcommand". I want to send the filename to another page. I have this code for the RowCommand event:
protected void gvFiles_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
if (e.CommandName == "sendcommand")
{
int index = Convert.ToInt32(e.CommandArgument);
string fileID = ((GridView)sender).DataKeys[index]["Name"].ToString();
Response.Redirect("irMain.aspx?#filename=" + fileID);
}
}
Nothing happens, except for a postback I think. How do I do this?
<asp:GridView ID="gvFiles" runat="server" Font-Name="Verdana" Font-Names="Verdana"
Width="401px" AutoGenerateColumns="False" BackColor="White"
BorderColor="Black" BorderStyle="Ridge" BorderWidth="2px"
DataKeyNames="Name,CreationTime"
>
<Columns>
<asp:HyperLinkField AccessibleHeaderText="File Name"
DataNavigateUrlFields="Name" DataNavigateUrlFormatString="~\Assets\reports\{0}"
DataTextField="Name" HeaderText="File Name" >
<HeaderStyle BackColor="#0033CC" ForeColor="White" />
</asp:HyperLinkField>
<asp:BoundField AccessibleHeaderText="Date" DataField="CreationTime"
DataFormatString="{0:d}" HeaderText="Date">
<HeaderStyle BackColor="Blue" ForeColor="White" />
</asp:BoundField>
<asp:ButtonField ButtonType="Button" Text="DO Stuff" CommandName="sendcommand"
HeaderText="WHAT?!" />
</Columns>
<AlternatingRowStyle BackColor="#6699FF" />
</asp:GridView>
You have to add the OnRowCommand attribute to your GridView in the ASPX, otherwise the GridView doesn't know what method to call when you execute a command on it.
AFAIK this is an entirely optional attribute and isn't generated via the designer so you have to add it manually when you want to use it.
Related
I have Web Form in ASP.NET in which I would like to show a table with all users in my app. There should be user name, user email, last activity date and user roles.
Currently I has this:
<asp:DataGrid id="UserGrid" runat="server"
CellPadding="2" CellSpacing="1"
Gridlines="Both" AutoGenerateColumns="false">
<Columns>
<asp:BoundColumn DataField="UserName" ReadOnly="False" HeaderText="Name" />
<asp:BoundColumn DataField="Email" ReadOnly="True" HeaderText="Email" />
<asp:BoundColumn DataField="LastActivityDate" ReadOnly="True" HeaderText="Last activity"/>
</Columns>
<HeaderStyle BackColor="darkblue" ForeColor="white" />
</asp:DataGrid>
_
UserGrid.DataSource = Membership.GetAllUsers();
UserGrid.DataBind();
I would like to add column roles to this DataGrid. How can I do that?
In the next step I want to add column with buttons to edit users info, manage his roles etc.
Add the columns your GridView as shown below
<asp:GridView id="UserGrid" runat="server"
CellPadding="2" CellSpacing="1"
Gridlines="Both" AutoGenerateColumns="false">
<Columns>
<asp:BoundColumn DataField="UserName" ReadOnly="False" HeaderText="Name" />
<asp:BoundColumn DataField="Email" ReadOnly="True" HeaderText="Email" />
<asp:BoundColumn DataField="LastActivityDate" ReadOnly="True" HeaderText="Last activity"/>
<asp:TemplateField HeaderText="User Roles" ItemStyle-Width="30%">
<ItemTemplate>
<asp:Label ID="lblrole" runat="server" %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="darkblue" ForeColor="white" />
</asp:GridView>
Declare a global variable for holding your user roles.
string[] roles;
In page load get your data
protected void page_load(object sender,EventArgs e)
{
if(!IsPostBack)
{
string[] roles=GetUserRoles();
}
}
In your RowDataBound event add the data to your gridview
protected void UserGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType= DataControlRowType.DataRow)
{
e.Row.FindControl("lblrole").Text=roles[e.Row.RowIndex];
}
}
If data order is not matching then sort both the collections.Here DataField is your database column name or the alias name you are using in your query
I have a problem in gridview, as per requirement i have set No of Records per page = 4 in gridview. I have to select Checkbox against every complaint but problem is then when i got to next pge in gridview and e.g fro 1 to 2 then when i come back to page 1 then it doesn't show TICK in check boxes . It doesn't remember my selection when i browse to and back to page.
<asp:GridView ID="GridViewSmsComplaints" AllowPaging="True" PageSize="4" runat="server" AutoGenerateColumns="False" CssClass="mGrid" BorderColor="#333333" Width="550px" OnPageIndexChanging="GridViewSmsComplaints_PageIndexChanging" >
<Columns>
<asp:BoundField HeaderText="ID" DataField="ID" />
<asp:BoundField HeaderText="Recieving Date" DataField="RecievingDate" />
<%--<asp:BoundField HeaderText="ToMobileNo" DataField="ToMobileNo" /> --%>
<asp:BoundField HeaderText="FromMobileNo" DataField="FromMobileNo" />
<asp:BoundField HeaderText="Message" DataField="Message" >
<ItemStyle Wrap="True" />
</asp:BoundField>
<asp:TemplateField HeaderText="IsComplaint">
<ItemTemplate>
<asp:CheckBox ID="ckboxIsComplaint" runat="server" Checked='<%# Convert.ToBoolean(Eval("IsComplaint").ToString()) %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
please check the above link.here your problem was clearly explained here.i think so it may be helpfull
As per comments...
If you do not update the underlying database by processing the OnCheckChanged event of the check box, then it will simply be reading the same data all the time.
From How to add event for Checkbox click in Asp.net Gridview Column, I have extracted the required information and tried to modify to fit your initial question.
<asp:TemplateField HeaderText="IsComplaint">
<ItemTemplate>
<asp:CheckBox ID="ckboxIsComplaint" runat="server" Checked='<%# Convert.ToBoolean(Eval("IsComplaint").ToString()) %>' OnCheckedChanged="chk_CheckedChanged" AutoPostBack="true/>
</ItemTemplate>
</asp:TemplateField>
add checkbox change event in aspx.cs page
protected void chk_CheckedChanged(object sender, EventArgs e)
{
GridViewRow row = ((GridViewRow)((CheckBox)sender).NamingContainer);
<your data source>.Rows[row.DataItemIndex]["B"] = ((CheckBox)GridViewSmsComplaints.Rows[row.RowIndex].FindControl("ckboxIsComplaint")).Checked;
}
I've seen lots of posts out there for this question, however, they all suggest we use methods like: dgv.CurrentCell or dgv.Rows[row].Cells[cellno].Selected. Intellisense finds no such methods. I have a textbox in a gridview, where I use the OnTextChanged method. Then, in my C# code, I update this quantity, then the grid refreshes automatically, and goes back to the top row, even though we've scrolled down a couple of pages. I've also tried putting in the MaintainScrollPositionOnPostback="true" in the 'Page' section of my .aspx page and that didn't seem to do anything. We're on .Net Framework 4.0.
<asp:GridView ID="gvOrderDetails" runat="server" AlternatingRowStyle-BackColor="#FAFAFA" Width="940px" AutoGenerateColumns="False" AllowSorting="True" OnSorting="SortOrderDetails"
OnRowCommand="gvOrderDetails_RowCommand" EmptyDataText="No Data to Display"
DataKeyNames="STOREORDNUM" HeaderStyle-Height="22px"
onselectedindexchanged="gvOrderDetails_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" /><EditRowStyle BackColor="#2461BF"/>
<FooterStyle BackColor="LightGray" Font-Bold="False" ForeColor="Black" />
<HeaderStyle BackColor="LightGray" Font-Bold="False" ForeColor="Black" BorderWidth="1px" BorderColor="Gray"/><PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" Height="22px"/>
<Columns>
<asp:BoundField DataField="ITMCD" HeaderText="Item Code" SortExpression="ItemCode" >
</asp:BoundField>
....
<asp:TemplateField HeaderText="Order Qty" SortExpression="OrderQty" >
<ItemTemplate>
<asp:TextBox ID="OrderQty" runat="server" Width="36" MaxLength="5" class="numberinput" AutoPostBack="true" OnTextChanged="buttonUpdateQty_Click" Text='<%# Bind("ORDERQTY") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In the code behind, I've tried these two things:
gvOrderDetails.Rows[row.RowIndex].FindControl("OrderQty").Focus();
gvOrderDetails.Rows[row.RowIndex].Cells[7].Controls[0].Focus();
You need to cast the required cotrol cell into Textbox control and then call the Focus() method on it.
Try This:
TextBox txtOrderQty = (TextBox) gvOrderDetails.Rows[row.RowIndex].FindControl("OrderQty");
txtOrderQty.Focus();
Add a handler to SelectedindexChange Event of your grid view
Gridview1.SelectedRow.Focus();
is there a way I can create a popup or dialog window from inside a gridview's ItemCommand event?
What I am trying to do is if the transaction failed, I want to show the error message in a popup when they click the image button.
This is as far as I have gotten. Also how can I put the error message into the dialog? Should I save the message to the grid view in a hidden column? I'm not sure how to pass that value into the dialog box.
the ascx
<telerik:RadGrid ID="TransactionListGrid" CssClass="DataGrid" AutoGenerateColumns="False" runat="server" AllowSorting="True"
AllowPaging="True" GridLines="None" EnableEmbeddedSkins="false" Skin="Growll" Width="700px" OnNeedDataSource="TransactionListGrid_NeedDataSource"
ShowHeadersWhenNoRecords="true" CellSpacing="0" OnItemDatabound="TransactionListGrid_ItemDataBound" OnItemCommand="TransactionListGrid_ItemCommand">
<ClientSettings EnableRowHoverStyle="true">
<Selecting AllowRowSelect="True"></Selecting>
</ClientSettings>
<PagerStyle Position="Top" />
<MasterTableView DataKeyNames="Id,Amount,IsCredit,IsCancelled" CommandItemDisplay="Top">
<NoRecordsTemplate>
<div>
No transactions found.</div>
</NoRecordsTemplate>
<CommandItemSettings ShowAddNewRecordButton="false" />
<Columns>
<telerik:GridDateTimeColumn HeaderText="Date" DataField="Date" />
<telerik:GridBoundColumn HeaderText="Order ID" DataField="Order_Id" />
<telerik:GridCheckBoxColumn HeaderText="Credit" DataField="IsCredit" />
<telerik:GridCheckBoxColumn HeaderText="Cancelled" DataField="IsCancelled" />
<telerik:GridCheckBoxColumn HeaderText="Failed" DataField="IsFailed" UniqueName="FailedCheckBox"/>
<telerik:GridButtonColumn HeaderText="Error" UniqueName="ErrorMessageButton" ButtonType="ImageButton"/>
<telerik:GridNumericColumn HeaderText="Amount" DataField="Amount" DecimalDigits="2" DataFormatString="{0:$######0.00}" />
<telerik:GridBoundColumn HeaderText="Last Four" DataField="CardLastFour" />
</Columns>
</MasterTableView>
</telerik:RadGrid>
c#
protected void TransactionListGrid_ItemCommand(object sender, GridCommandEventArgs e)
{
if (e.CommandName == "ErrorMessage")
{
}
}
There are a few ways to do this, but the easiest way is probably using AJAX. Put a RadToolTip on your page and ajaxify the tooltip and grid using the RadAjaxManager (or RadAjaxPanel). With the tooltip and grid ajaxified, you can just call the RadToolTip.Show() method in the ItemCommand event of the grid.
I want the headers of my gridview to be hyperlinks, without the "SortExpression"...
I searched the net, but I've been not very succesful.
Anyone has the solution?
For example: when clicking on the header of a simple gridview, the site navigates to a webpage. Is it possible?
Thanks in advance!
Have you tried Gridview Header template like...
<asp:GridView runat="server" ID="grd">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:HyperLink runat="server" NavigateUrl="YourURL"> </asp:HyperLink>
</HeaderTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I think a HeaderTemplate is needed here...
Ref.: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.templatefield.headertemplate.aspx
HTH.
Now I got this gridview, And I need the headers to be clickable, whereafter an event starts (something like OnClickHeader="header_ClickEvent"?) Ofcourse there is a SortExpression element, which enables to sort the grid, but I want to be able to start any event, like when clicking a button.
I could not find any solution within the asp:BoundField nor asp:TemplateField...
I thought a hyperlink could solve the problem, but that was a bit premature.
The Gridview:
<asp:GridView CssClass="gridview" ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="Student_key" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" PagerSettings-Visible="false" PageSize="14">
<HeaderStyle CssClass="headerstyle" />
<RowStyle CssClass="rowstyle"/>
<AlternatingRowStyle CssClass="altrowstyle" />
<Columns>
<asp:BoundField DataField="Studentnumber" HeaderText="Studentnummer" >
<HeaderStyle CssClass="header100" />
</asp:BoundField>
<asp:BoundField DataField="Prefix" HeaderText="Voorletters" >
<HeaderStyle CssClass="header75" />
</asp:BoundField>
<asp:BoundField DataField="prename" HeaderText="Voornaam" SortExpression="Voornaam">
<HeaderStyle CssClass="header75" />
</asp:BoundField>
<asp:BoundField DataField="nickname" HeaderText="Roepnaam" >
<HeaderStyle CssClass="header100" />
</asp:BoundField>
<asp:BoundField DataField="insertion" HeaderText="Tussenvoegsel" >
<HeaderStyle CssClass="header100" />
</asp:BoundField>
<asp:BoundField DataField="surname" HeaderText="Achternaam">
<HeaderStyle CssClass="header100" />
</asp:BoundField>
<asp:CommandField SelectText="show results" ShowSelectButton="True" >
<HeaderStyle CssClass="header100" />
</asp:CommandField>
</Columns>
<EmptyDataTemplate >There are no results shown, please try again.</EmptyDataTemplate>
</asp:GridView>
I used a method that might be a little unconventional but it works. In my case I wanted to use the standard BoundField controls in my gridview as opposed to using a template field with both a HeaderTemplate and ItemTemplate. I used a simple gridview based on a SQL datasource that looks like this.
<asp:GridView
ID="gvTopXByContest"
runat="server"
AutoGenerateColumns="False"
DataSourceID="dsTopXByContest"
AllowSorting="true"
OnSorting="gvTopXByContest_OnSorting" >
<Columns>
<asp:BoundField DataField="txtOnlineUserName" HeaderText="Fan Name & Rank" SortExpression="txtOnlineUserName" ItemStyle-Width="155px"></asp:BoundField>
<asp:BoundField DataField="fltTotalPoints" HeaderText="Points" SortExpression="fltTotalPoints" ItemStyle-Width="40px"></asp:BoundField>
<asp:BoundField DataField="curWon" HeaderText="Won" SortExpression="curWon" ItemStyle-Width="40px"></asp:BoundField>
</Columns>
</asp:GridView>
I then used code that fires on the OnSorting event of the gridview to do my redirects
Protected Sub gvTopXByContest_OnSorting(sender As Object, e As GridViewSortEventArgs)
If e.SortExpression <> DirectCast(sender, GridView).SortExpression Then
If e.SortExpression = "txtOnlineUserName" Then
Response.Redirect(URL to redirect to goes here)
ElseIf e.SortExpression = "fltTotalPoints" Then
Response.Redirect(URL to redirect to goes here)
Else
'I could have used another ElseIf here but since there are only 3 columns Else works
Response.Redirect(URL to redirect to goes here)
End If
End Sub