I have a GridView:
<asp:GridView ID="gridSearchResults" AutoGenerateColumns="false" DataKeyNames="uid" runat="server"
AllowSorting="true" AutoGenerateSelectButton="true" CssClass="table table-striped table-bordered"
OnRowDataBound="gridSearchResults_RowDataBound"
OnSelectedIndexChanged="gridSearchResults_UserSelected">
<Columns>
<asp:BoundField DataField="uid" HeaderText="UID" SortExpression="uid" ItemStyle-Width="30%"/>
<asp:BoundField DataField="givenName" HeaderText="First Name" SortExpression="givenName" ItemStyle-Width="35%" />
<asp:BoundField DataField="sn" HeaderText="Last Name" SortExpression="sn" ItemStyle-Width="35%" />
</Columns>
</asp:GridView>
With `AutoGenerateSelectButton="true" a "select" button appears in every row. I can click on this and fire:
`protected void gridSearchResults_UserSelected(object sender, EventArgs e) {
// Get the user's ID from the selected row
idNumber.Text = gridSearchResults.SelectedRow.Cells[1].Text;
firstName.Text = gridSearchResults.SelectedRow.Cells[2].Text;
lastName.Text = gridSearchResults.SelectedRow.Cells[3].Text;
}
which works. However, I would like to remove the "select" button and be able to press anywhere in the row to populate the TextBoxes.
This is the code for gridSearchResults_RowDataBound, which should handle the row click:
protected void gridSearchResults_RowDataBound(object objSender, GridViewRowEventArgs gridViewRowEventArgs) {
if (gridViewRowEventArgs.Row.RowType == DataControlRowType.DataRow) {
// Setup click handler and cursor
//gridViewRowEventArgs.Row.Attributes["onclick"] = DONT KNOW WHAT TO ADD HERE
gridViewRowEventArgs.Row.Attributes["style"] = "cursor:pointer";
// Implement row mouseover and mouseout
gridViewRowEventArgs.Row.Attributes.Add("onmouseover", "this.originalStyle=this.style.backgroundColor; this.style.backgroundColor='#B3E5FC';");
gridViewRowEventArgs.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.originalStyle;");
}
}
I have seen something like e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(grdSearchResults, "Select$" + e.Row.RowIndex); but I'm not sure how to mix the two.
Thanks in advance for any help!
The answer can be found here; https://www.aspsnippets.com/Articles/Selecting-GridView-Row-by-clicking-anywhere-on-the-Row.aspx
For my solution I needed to modify a couple of things. In gridSearchResults_RowDataBound I need to add:
gridViewRowEventArgs.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(gridSearchResults, "Select$" + gridViewRowEventArgs.Row.RowIndex);
In gridSearchResults_UserSelected I needed to update the Cell indices.
Related
We have a webform with a radgrid and a button. The radgrid has two columns and a checkbox column.
On Page_load, the data will be displayed and the user will be able to select (via the checkbox) which rows will go through with the update of the EmpId; if the row is selected, NewEmpId will replace OldEmpId. The Update button is clicked and the changes are made.
The problem I'm having is that I prefer to use the datakeynames to retrieve the data from each row. But I'm having trouble implementing it without using GridCheckBoxColumn, which I don't want to use because the radgrid needs to be in Edit mode for the checkbox to be selected, and that brings other issues.
<telerik:RadGrid ID="RadGridEmp" runat="server" AutoGenerateColumns="False" Width="100%" AllowPaging="True" PageSize="22">
<ClientSettings>
<Selecting AllowRowSelect="True" />
</ClientSettings>
<mastertableview commanditemdisplay="TopAndBottom" datakeynames="OldEmpId, NewEmpId, EmpName">
<commanditemsettings showaddnewrecordbutton="false" />
<Columns>
<telerik:GridBoundColumn DataField="OldEmpId" HeaderText="OldEmpId">
<HeaderStyle Width="110px"></HeaderStyle>
</telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="NewEmpId" HeaderText="NewEmpId">
<HeaderStyle Width="110px"></HeaderStyle>
</telerik:GridBoundColumn>
<ItemTemplate>
<asp:CheckBox ID="ChkChange" runat="server" />
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</mastertableview>
</telerik:RadGrid>
The following code is just the code I prefer to use with this issue. It uses datakeynames. But it doesn't build:
protected void RadButtonUpdateSectors_Click(object sender, EventArgs e)
{
foreach (GridItem item in RadGridEmp.MasterTableView.Items)
{
GridDataItem dataitem = (GridDataItem)item;
TableCell cell = dataitem["GridCheckBoxColumn"];
CheckBox checkBox = (CheckBox)cell.Controls[0];
if (checkBox.Checked)
{
oldEmpId = dataitem.GetDataKeyValue("OldEmpId").ToString();
newEmpId = dataitem.GetDataKeyValue("NewEmpId").ToString();
UpdateEmpId(oldEmpId, newEmpId, connString);
}
}
}
Please try with the below code snippet.
datakeynames="OldEmpId,NewEmpId,EmpName"
...............
...............
protected void RadButtonUpdateSectors_Click(object sender, EventArgs e)
{
foreach (GridDataItem item in RadGridEmp.MasterTableView.Items)
{
CheckBox ChkChange = item.FindControl("ChkChange") as CheckBox;
if (ChkChange.Checked)
{
string oldEmpId = item.GetDataKeyValue("OldEmpId").ToString();
string newEmpId = item.GetDataKeyValue("NewEmpId").ToString();
UpdateEmpId(oldEmpId, newEmpId, connString);
}
}
}
Let me know if any concern.
Note:- Remove extra space from datakeynames.
I am trying to complete a simple task;
a gridview column gets an integer data if integer is equals to zero print "active" and set the commandname of the linkbutton to active else set linkbutton text and command value to inactive.
here is what I have so far
<Columns>
<asp:BoundField HeaderText = "User Name" DataField="UserName"
HeaderStyle-Width="16%" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField HeaderText = "Role" DataField="RoleNAME"
HeaderStyle-Width="14%" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField HeaderText = "Group" DataField="GroupName"
HeaderStyle-Width="12%" ItemStyle-HorizontalAlign="Center" />
<asp:ButtonField ButtonType="link" CommandName = "Active"
HeaderText="Status" Text="Active"
HeaderStyle-Width="10%" ItemStyle-HorizontalAlign="Center" />
<asp:ButtonField ButtonType="link" CommandName = "Edit"
HeaderText="" Text="Edit/View"
HeaderStyle-Width="10%" ItemStyle-HorizontalAlign="Center" />
</Columns>
codebehind
protected void grdMyQueue_RowdataBound(object sender, GridViewRowEventArgs e)
{
// In template column,
if (e.Row.RowType == DataControlRowType.DataRow)
{
var obj = (User)e.Row.DataItem;
if (obj.isDisabled == 0)
{
LinkButton linkButton = new LinkButton();
linkButton.Text = "Active";
linkButton.Enabled = true;
linkButton.CommandName = "Active";
//linkButton.CommandArgument = e.Row. //this might be causing the problem
e.Row.Cells[3].Controls.Clear();
e.Row.Cells[3].Controls.Add(linkButton);
}
else
{
LinkButton linkButton = new LinkButton();
linkButton.Text = "InActive";
linkButton.Enabled = true;
linkButton.CommandName = "InActive";
e.Row.Cells[3].Controls.Add(linkButton);
}
}
}
However when I Click the active linkbutton on the cell I get an error at onrowcommand function
protected void OnRowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument); // this is the error line
GridViewRow gvRow = userManager.Rows[index];
TableCell usrName = gvRow.Cells[0];
string userName = usrName.Text;
....
How can I manage to change LinkButton text and CommandName depending on that integer data?
P.S I tried Eval but I couldnt figure out whats going on....
I would simply return the data from your data source, as intended. Then I would use an Update Panel to avoid the Postback that will occur from your Link Button. As for the text modifying I would use Javascript, so Javascript will read the page on the client. So when your data source returns:
One
One
Two
One
The Javascript can analyze those rows, then modify the internal cell within the Grid quite painless.
An example of Javascript:
$(".Activator").each(function () {
if ($(this).prev().find(':checkbox').prop('checked')) {
$(this).text("Deactivate");
}
});
This example will validate if a checkbox is checked, if it is modify the internal text to the class .Activator.
Then the internal item in the Grid for code on front-end would look like:
<asp:TemplateField HeaderText="Active">
<ItemTemplate>
<asp:CheckBox
ID="CustomerCheck" runat="server"
Checked='<%# Eval("Active") %>'
Enabled="false" />
<asp:LinkButton
ID="lbCustomerActive" runat="server"
Text="Activate"
CommandName="OnActivate"
ToolTip='<%# "Activate or Deactivate Course: " + Eval("CourseID") %>'
OnClick="CustomerCheck_Click"
CssClass="Activator">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
As you can see, as the internal data is changed the Javascript will automatically adjust the value for me every time the Data Source is binded again. Which the CustomerCheck_Click would execute the code on the server, which will read the Command Argument which contains the Row Id. Which will Update that particular record without a problem and rebind the Grid. (Partially lied, I'm parsing the Tooltip).
You would instantiate on server side like:
((LinkButton)sender).ToolTip;
I've done some searching prior to asking, and although this post is close, it doesn't work for my scenario.
What I find is that the "delete" button in my template field seems to fire, but the click event does not trigger. Yet the second time you click the button it works as expected.
So, breaking the code down, I am binding my data to a GridView, using a `SqlDataSource.
My page load event starts as follows:
if (!Page.IsPostBack)
{
externalUserDataSource.ConnectionString = "some connection string";
}
My data source is as follows:
<asp:SqlDataSource ID="externalUserDataSource" runat="server"
ConflictDetection="CompareAllValues" SelectCommand="uspGetExternalUsersByTeam"
SelectCommandType="StoredProcedure" ProviderName="System.Data.SqlClient">
<SelectParameters>
<asp:SessionParameter Name="TeamID" SessionField="TeamID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
And this is my GridView markup:
<asp:GridView ID="gridView" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px"
CellPadding="4" DataKeyNames="LoginID" DataSourceID="externalUserDataSource"
EnableModelValidation="True" OnRowDataBound="GridViewRowDataBound" TabIndex="3">
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="White" />
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
<RowStyle BackColor="LightGoldenrodYellow" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<Columns>
<asp:BoundField DataField="RowID" HeaderText="Row ID" ReadOnly="True"
SortExpression="RowID" Visible="False" />
<asp:BoundField DataField="LoginID" HeaderText="Login ID" ReadOnly="True"
SortExpression="LoginID" Visible="False" />
<asp:BoundField DataField="EmailAddress" HeaderText="Email Address"
ItemStyle-VerticalAlign="Bottom" ReadOnly="True" SortExpression="AssociateName"/>
<asp:BoundField DataField="TeamID" HeaderText="Team ID" ReadOnly="True"
SortExpression="TeamID" Visible="False" />
<asp:CheckBoxField DataField="HasFIAccess"
HeaderText="Has Access to<br />Funding<br/>Illustrator"
ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Bottom"
ReadOnly="True"/>
<asp:CheckBoxField DataField="HasALTAccess"
HeaderText="Has Access to<br />Asset Liability<br/>Tracker"
ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Bottom"
ReadOnly="True"/>
<asp:CheckBoxField DataField="HasFIAAccess"
HeaderText="Has Access to<br />Funding<br/>Illustrator App"
ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Bottom"
ReadOnly="True"/>
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" CssClass="additionsRow" ID="btnDeleteExternalUser" OnClick="DeleteExtUserButtonClick"
CausesValidation="False" Text="Delete"
CommandArgument='<%#Eval("TeamID") + "," + Eval("LoginID") + "," + Eval("EmailAddress") + "," + Eval("HasALTAccess")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
So, you can see that I am passing across some information in the button that is used in the event to ensure the correct data is deleted (which is why I cannot use the ButtonField, as suggested in the link above).
The last part to the puzzle is the GridView's databound event:
protected void GridViewRowDataBound(object sender,
GridViewRowEventArgs e)
{
// if rowtype is not data row...
if (e.Row.RowType != DataControlRowType.DataRow)
{
// exit with no further processing...
return;
}
// get the ID for the selected record...
var selectedId = DataBinder.Eval(e.Row.DataItem, "RowID").ToString();
// create unique row ID...
e.Row.ID = string.Format("ExtUserRow{0}", selectedId);
// find the button delete for the selected row...
var deleteButton = (Button)e.Row.FindControl("btnDeleteExtUser");
// get the email address for the selected record...
var selectedUser = DataBinder.Eval(e.Row.DataItem, "EmailAddress").ToString();
// define the message text...
var messageText = string.Format("OK to delete {0}?",
selectedUser.Replace("'", "\\'"));
// add attribute to row delete action...
this.AddConfirmMessage(deleteButton, messageText);
}
Where AddConfirmMessage simply assigns an onclick attribute to the control to ensure the user has to confirm the deletion.
Now, in every case the message pops up 'OK to delete abc#xyz.com?', but as stated earlier, the event assigned to the "delete" button does not trigger until the button is clicked a second time.
Strangely enough, I took this code from another page and modified accordingly, though it doesn't have this issue there:
protected void DeleteExtUserButtonClick(object sender,
EventArgs e)
{
// get the buton which was clicked...
var button = (Button)sender;
// break the delimited array up...
string[] argumentArray = button.CommandArgument.Split(',');
// store the items from the array...
string teamId = argumentArray[0];
string loginId = argumentArray[1];
string emailAddress = argumentArray[2];
string hasAltAccess = argumentArray[3];
using (var conn = new SqlConnection(Utils.GetConnectionString()))
{
// create database command...
using (var cmd = new SqlCommand())
{
// set the command type...
cmd.CommandType = CommandType.StoredProcedure;
// set the name of the stored procedure to call...
cmd.CommandText = "uspDeleteExternalUser";
// create and add parameter to the collection...
cmd.Parameters.Add(new SqlParameter("#TeamId", SqlDbType.Int));
// assign the search value to the parameter...
cmd.Parameters["#TeamId"].Value = teamId;
// create and add parameter to the collection...
cmd.Parameters.Add(new SqlParameter("#LoginId", SqlDbType.VarChar, 50));
// assign the search value to the parameter...
cmd.Parameters["#LoginId"].Value = loginId;
// set the command connection...
cmd.Connection = conn;
// open the connection...
conn.Open();
// perform deletion of user...
cmd.ExecuteNonQuery();
}
}
// bind control to refresh content...
ExtUsersGrid.DataBind();
}
Have I missed something obvious? I am happy to modify if there are better ways to do this.
Edit 1: Following on from the discussions below, I have modified the following:
Removed the Onclick event property of the ButtonItem;
Set the CommandName and CommandArgument as suggested below, and updated the DataKeyNames to use RowID which is a unique ID from the data;
Assigned a RowCommand event for the GridView;
Assigned the delete code to the RowCommand event.
Following these changes, it still fires the row event code on the second click.
Edit 2: FYI - I've now removed the SqlDataSource and the associated code/references, and created a procedure to fill the dataset, which is called on Page_Load (inside the !Page.IsPostBack brackets). I started making the changes below to use the RowCommand event, but they still caused the same issue (i.e. the button will only fire on the second click). As using RowCommand meant converting the BoundFields to ItemTemplates, I reverted back to the button click event as it seemed pointless making all those changes for no gain. If anyone else can help me understand why it only triggers on the second click, would appreciate your input.
OK, frustratingly this was due to some code that for reasons still unknown, works elsewhere.
In the DataBound event, there was two lines of code:
// get the associate name for the selected record...
var selectedId = DataBinder.Eval(e.Row.DataItem, "RowID").ToString();
// create unique row ID...
e.Row.ID = string.Format("ExtUserRow{0}", selectedId);
The process of applying an ID to the rows programatically seems to break the connection between the data and the events.
By removing these two lines of code, it works as expected.
Well instead you can do something like this.
Add a CommandName property to your GridView like this. Also note the changes in the CommandArgument property:
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" CssClass="additionsRow" ID="btnDeleteExtUser"
CausesValidation="False" Text="Delete"
CommandName="OnDelete"
CommandArgument='<%# Container.DisplayIndex %>" '
</ItemTemplate>
</asp:TemplateField>
Code behind will look something like this. Note that I am using the RowCommand event of Gridview.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "OnDelete")
{
int rowIndex = Convert.ToInt32(e.CommandArgument);
// now you got the rowindex, write your deleting logic here.
int ID = Convert.ToInt32(myGrid.DataKeys[rowIndex]["ID"].Value);
// id will return you the id of the row you want to delete
TextBox tb = (TextBox)GridView1.Rows[rowIndex].FindControl("textboxid");
string text = tb.Text;
// This way you can find and fetch the properties of controls inside a `GridView`. Just that it should be within `ItemTemplate`.
}
}
Note: mention DataKeyNames="ID" inside your GridView. The "ID" is the primary key column of your table.
Are you binding the GridView on pageload? If so, then move it to !IsPostBack block as show below:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = yourDataSource;
GridView1.DataBind();
}
}
//code in aspx file:
<html>
<body>
<form>
<asp:GridView ID="grid" runat="server" AutoGenerateColumns="False"
onselectedindexchanged="grid_SelectedIndexChanged" >
<Columns>
<asp:BoundField DataField="RollID" HeaderText="RollID" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:ButtonField CommandName="Select" Text="Select" />
</Columns>
</asp:GridView>
</div><br />
<asp:label ID="Label" runat="server" text=""></asp:label>
</form>
</body>
</html>
//code behind file:
protected void grid_SelectedIndexChanged(object sender, GridViewRowEventArgs e)
{
RowIndex = grid.SelectedIndex;
GridViewRow row = grid.Rows[RowIndex];
string a = row.Cells[4].Text;
Label.Text = "You selected " + a + ".";
}
!!! The question is,though iam able to print the data in the grid view form,but when i select a row,i could not print out the message"You selected..etc.." with the use of "Label" server control.
"could any1 plz sort m out dis issue"...
Don't use the SelectedIndexChanged event. Instead, use the RowCommand event:
protected void grid_RowCommand(object sender, GridViewCommandEventArgs e) {
if (e.CommandName == "Select") {
int RowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow row = grid.Rows[RowIndex];
string a = row.Cells[4].Text;
Label.Text = "You selected " + a + ".";
}
}
MSDN Link: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand.aspx
How are you selecting a row? You may want to set this attribute on the gridview to allow selection to even take place (that the gridview is aware of) by allowing the control to generate a button:
AutoGenerateSelectButton="True"
You can see more information about this here. Of course, this isn't the only way to create a command button, but you'll have to followup if it won't suit your purposes.
In reference to Link loaded into my gridview try to navigate to my local server. The columns I have in the datagrid are Customer #, Description, Link.
I've got a function set up that's called on rowDataBound, but how do I retrieve what link is in the row so that I can edit it, and then rebind it to the datagrid?
protected void grdLinks_RowDataBound( object sender, GridViewRowEventArgs e )
{
if ( e.Row.RowIndex == 2 )
{
}
}
And here is my gridview code
<asp:GridView ID="grdLinks" runat="server" AutoGenerateColumns="False" DataSourceID="ldsCustomerLinks"
OnRowDataBound="grdLinks_RowDataBound" EmptyDataText="No data was returned."
DataKeyNames="ID" OnRowDeleted="grdLinks_RowDeleted" Width="80%" BackColor="White"
HorizontalAlign="Center" BorderColor="#999999" BorderStyle="None" BorderWidth="1px"
CellPadding="3" GridLines="Vertical">
<RowStyle BackColor="#EEEEEE" ForeColor="Black" />
<Columns>
<asp:BoundField DataField="CustomerNumber" HeaderText="Customer Number" SortExpression="CustomerNumber" />
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:HyperLinkField DataTextField="Link" HeaderText="Link" SortExpression="Link" DataNavigateUrlFields="Link" Target="_blank" />
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="ldsCustomerLinks" runat="server" ContextTypeName="ComplianceDataContext"
TableName="CustomerLinks" EnableDelete="true">
</asp:LinqDataSource>
If I'm understanding you correctly, you want to get the value of a data item called Link. If so, then something like this should work:
EDIT: I think what you're saying is that you want to grab the value Link from the database, manipulate it and then set the Url of the HyperLink to the new, manipulated value, if so then it would look like this:
ASPX Page (Updated to reflect posted code)
<Columns>
<asp:BoundField DataField="CustomerNumber" HeaderText="Customer Number" SortExpression="CustomerNumber" />
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:TemplateField HeaderText="Link">
<ItemTemplate>
<asp:HyperLink ID="hlParent" runat="server" Text='<% #(Eval("Link")) %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
I modified the ASP from your original question by adding an ID and removing the reference to the NavigateUrl attribute from the HyperLink control.
Code
protected void grdLinks_RowDataBound( object sender, GridViewRowEventArgs e )
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string link = DataBinder.Eval(e.Row.DataItem, "Link") as string;
if (link != null && link.Length > 0)
{
// "FindControl" borrowed directly from DOK
HyperLink hlParent = (HyperLink)e.Row.FindControl("hlParent");
if (hlParent != null)
{
// Do some manipulation of the link value
string newLink = "https://" + link
// Set the Url of the HyperLink
hlParent.NavigateUrl = newLink;
}
}
}
}
RowDataBound is called for every row in the GridView, including headers, footers, etc. Therefore, you should start by examining only the rows containing data.
Once you're on a row, there are several ways to examine the cells. One is just to use the cell index (2 here). That seems simple in your situation, but will lead to frustration if you ever rearrange the columns.
Here's an example of that from MSDN:
void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Display the company name in italics.
e.Row.Cells[1].Text = "<i>" + e.Row.Cells[1].Text + "</i>";
}
A better way is to use FindControl with the item's ID.
protected void gvBarcode_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hlParent = (HyperLink)e.Row.FindControl("hlParent");
}
}
You may also want to look into letting the gridview do it for you.
You can use the datanavigateurlformatstring property to insert querystring parameters if that's what you are trying to do.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hyperlinkfield.datanavigateurlformatstring.aspx