I have a datagrid in asp.net, with a boundfield. On the RowCommand event, I want to get the value of this boundfield. The boundfield, in the columns tag, loooks as below:
<asp:BoundField DataField="LoginID" HeaderText="LoginID" InsertVisible="False"
ReadOnly="True" SortExpression="LoginID" />
What would the accompanying C# be?
Thanks
In the Row_Command Event you can retrieve the index of the clicked Row in this way :
void GridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
//Check if it's the right CommandName...
if(e.CommandName=="Add")
{
//Get the Row Index
int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row
GridViewRow row = ContactsGridView.Rows[index];
// Here you can access the Row Cells
row.Cells[1].Text
}
}
protected void gv_research_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "editResearch")
{
txt_researchName.Text = gv_research.Rows[index].Cells[1].Text.TrimEnd();
}
}
catch (Exception ee)
{
string message = ee.Message;
}
}
.aspx:
<asp:ImageButton ID="btn_Edit" runat="server" CommandArgument='<%#((GridViewRow)Container).RowIndex%>' CommandName="editResearch" />
Related
<asp:TemplateField HeaderText="ID" SortExpression="CareerFormID">
<ItemTemplate>
<asp:Label ID="CareerFormID" runat="server" Text='<%#Eval("CareerFormID")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Checked" DataField="checked" />
<asp:ButtonField Text="Edit" CommandName="Select" ButtonType="Link" />
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
string idtemp = (GridView1.SelectedRow.FindControl("CareerFormID") as Label).Text;
Session["CompanyFormID"] = idtemp;
Response.Redirect("Management_Edit.aspx");
//Response.Write(Session["CompanyFormID"]);
}
I want to change ButtonField text="Modify" when DataField="checked" is 1, How can I do this?
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[4].Text == "1")
{
e.Row.Cells[4].Text = "Yes";
e.Row.Cells[4].ForeColor = System.Drawing.Color.Green;
e.Row.Cells[6].Text = "Modify";
}
else if (e.Row.Cells[4].Text == "0")
{
e.Row.Cells[4].Text = "No";
e.Row.Cells[4].ForeColor = System.Drawing.Color.Red;
}
}
}
But this don't work, the cells[6] text is changed but the link is cancel.
For Example like that, the link can not working when I change the text
http://i.imgur.com/CN5snv6.jpg
Makes event handler when DataField="checked" is 1 (I don't find it in your code, how to make it to 1) and do this
//begin of event handler
//check datafield="checked" is 1, I still don't get it this one
ButtonField.Text="Modify"
//end of event handler
I'm totally having trouble with a Gridview that's been stumping me all day. I don't use Gridviews very often so some of this is confusing me and Google hasn't been as much help as I was hoping.
I'm trying to bind an object created through LINQ to a gridview and then do some updating.
XAML:
<asp:GridView runat="server" ID="GV1"
onrowediting="gridViewUsers_RowEditing"
onrowcancelingedit="gridViewUsers_RowCancelingEdit"
onrowdeleting="gridViewUsers_RowDeleting"
onrowupdating="gridViewUsers_RowUpdating"
>
<Columns>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
Code:
private void BindGrid()
{
List<Room> stuff = new List<Room>();
Hotel = dc1.Rooms.ToList();
GV1.DataSource = Hotel;
GV1.DataBind();
}
protected void gridViewUsers_RowEditing(object sender, GridViewEditEventArgs e)
{
GV1.EditIndex = e.NewEditIndex;
BindGrid();
}
I want to just grab the Room object from the selected row and update it back to the database through LINQ. But I can't seem to get my hands on that object. My next attempt was to grab each entry from the row. So I found code like the example below. But everything is null.
protected void gridViewUsers_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string tenant = ((TextBox)(GV1.Rows[e.RowIndex].FindControl("Tenant"))).Text;
string age = ((TextBox)(GV1.Rows[e.RowIndex].FindControl("Age"))).Text;
string roomno = ((TextBox)(GV1.Rows[e.RowIndex].FindControl("Room_No"))).Text;
BindGrid();
}
Try to set AutoGenerateColumns = false and provide columns manually.
Something like:
<asp:GridView runat="server" ID="GV1"
onrowediting="gridViewUsers_RowEditing"
onrowcancelingedit="gridViewUsers_RowCancelingEdit"
onrowdeleting="gridViewUsers_RowDeleting"
onrowupdating="gridViewUsers_RowUpdating"
AutoGenerateColumns = "false"
>
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:BoundField HeaderText="Tenant" DataField="Tenant" />
<asp:BoundField HeaderText="Age" DataField="Age" />
<asp:BoundField HeaderText="Room_No" DataField="Room_No" />
</Columns>
</asp:GridView>
EDIT:
Please add this code to your solution
public static int GetCellIndexByFieldHandle(this GridView grid, string fieldHandle)
{
int iCellIndex = -1;
for (int iColIndex = 0; iColIndex < grid.Columns.Count; iColIndex++)
{
if (grid.Columns[iColIndex] is DataControlField)
{
DataControlField col = (DataControlField)grid.Columns[iColIndex];
if ((col is BoundField && string.Compare(((BoundField)col).DataField, fieldHandle, true) == 0)
|| string.Compare(col.SortExpression, fieldHandle, true) == 0
|| col.HeaderText.Contains(fieldHandle))
{
iCellIndex = iColIndex;
break;
}
}
}
return iCellIndex;
}
/// <summary>
/// Gets the ordinal index of a TableCell in a rendered GridViewRow, using a text fieldHandle (e.g. the corresponding column's DataFieldName/SortExpression/HeaderText)
/// </summary>
public static int GetCellIndexByFieldHandle(this GridViewRow row, string fieldHandle)
{
return GetCellIndexByFieldHandle((GridView)row.Parent.Parent, fieldHandle);
}
And try
string tenant = ((TextBox)GV1.Rows[e.RowIndex].Cells[GV1.Rows[e.RowIndex].GetCellIndexByFieldHandle("Tenant")].Controls[0]).Text;
Try this code to access your textbox values .
protected void gridViewUsers_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gridViewUsers.Rows[e.RowIndex];
Textbox txtbxtenant = (TextBox)row.FindControl("Tenant");
string tenanat = Convert.toString(tentant.text);
Textbox txtbxAge =(Textbox)row.FindControl("Age");
string age = Convert.toString(Age.text);
// string roomno = ((TextBox)
//(GV1.Rows[e.RowIndex].FindControl("Room_No"))).Text;
// BindGrid();
}
I have a custom grid on which i have binded data in my c# code behind. I have given a hyperlink field to one of my column. If i click the hyperlink value, it should navigate to the details page of that hyperlink value. The code is given below,
protected void grd_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink myLink = new HyperLink();
myLink.Text = e.Row.Cells[2].Text;
e.Row.Cells[2].Controls.Add(myLink);
myLink.NavigateUrl = "Estimation.aspx?EstimateID=" + EstimateID + "&VersionNo=" + VersionNo;
}
}
If i click the link, the page is getting navigated, but i am not getting the details which are already pre-loaded in that page. Please give me suggestions on how to incorporate this.
Thanks
You can use this to redirect, read this
<asp:HyperLink ID="HyperLink1"
runat="server"
NavigateUrl="Default2.aspx">
HyperLink
</asp:HyperLink>
to add attribute with link just add
HyperLink1.Attributes.Add ("");
You need to do a small change in the RowDataBound event
myLink.Attributes.Add("href"," your url");
You need to fetch the values for EstimateID and VersionNo from the grid row data. Take a look at the documentation for GridViewRowEventArgs and you'll see there's a .Row property.
So your code needs to be something like:
myLink.NavigateUrl = "Estimation.aspx?EstimateID=" + e.Row.Cells[4].Text + "&VersionNo=" + e.Row.Cells[5].Text;
Or, maybe you need to get to the data item associated with the grid row, in which case take a look at e.Row.DataItem, the GridViewRow.DataItem property. This DataItem will need to be cast to the type of data you've bound to the grid in order to fetch the data from it, which might be something like:
((MyCustomDataRow)e.Row.DataItem).EstimateID
Try below solution :
Page-1 that is your list page :
ASPX code :
<asp:GridView ID="GridView1" runat="server"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server">HyperLink</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind :
protected void Page_Load(object sender, EventArgs e)
{
List<Data> lstData = new List<Data>();
for (int index = 0; index < 10; index++)
{
Data objData = new Data();
objData.EstimateID = index;
objData.VersionNo = "VersionNo" + index;
lstData.Add(objData);
}
GridView1.DataSource = lstData;
GridView1.DataBind();
}
public class Data
{
public int EstimateID { get; set; }
public string VersionNo { get; set; }
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink HyperLink1 = e.Row.FindControl("HyperLink1") as HyperLink;
HyperLink1.NavigateUrl = "Details.aspx?EstimateID=" + e.Row.Cells[1].Text + "&VersionNo=" + e.Row.Cells[2].Text;
}
}
Page-2 that is your details page :
Code behind :
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Request.QueryString["EstimateID"].ToString());
Response.Write(Request.QueryString["VersionNo"].ToString());
}
I am using Datagrid control to populate list of items/contents. I want to show what row has been selected, distinctive.
What property of the datagrid control should i use ?
How do i do this ?
Thanks
Ron.
<SelectedItemStyle BackColor="Pink" ForeColor="Green" />
The SelectedRow Property is perhaps what you need
void CustomersGridView_SelectedIndexChanged(Object sender, EventArgs e)
{
// Get the currently selected row using the SelectedRow property.
GridViewRow row = CustomersGridView.SelectedRow;
// Display the company name from the selected row.
// In this example, the third column (index 2) contains
// the company name.
MessageLabel.Text = "You selected " + row.Cells[2].Text + ".";
}
Ron, DataGrid hasnt default behaviour for row selecting. You should do it yourself:
<asp:DataGrid runat="server" ID="DataGridTest" SelectedIndex="1" OnItemCreated="DataGridTest_ItemCreated" DataSourceID="DataSourceTmp">
<HeaderStyle BackColor="HighlightText" Font-Bold="true" />
<ItemStyle BackColor="White" />
<SelectedItemStyle BackColor="#bbbbff" />
</asp:DataGrid>
Code behind:
public partial class _Default : Page
{
private const string DataGridSelectedRowCssClass = "selectedRow";
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterClientScriptBlock(
GetType(),
"dataGrid_selectRow",
string.Format(
#"(function (dataGrid, $, undefined) {{
dataGrid.selectRow = function (row) {{
$(row).siblings('.{0}').css('background-color', '#{1}').end().css('background-color', '#{2}').addClass('{0}');
}}
}})(window.dataGrid = window.dataGrid || {{}}, jQuery);",
DataGridSelectedRowCssClass,
DataGridTest.ItemStyle.BackColor.ToArgb().ToString("X8").Substring(2),
DataGridTest.SelectedItemStyle.BackColor.ToArgb().ToString("X8").Substring(2)),
true);
}
protected void DataGridTest_ItemCreated(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.SelectedItem)
{
e.Item.Attributes["onclick"] = "dataGrid.selectRow(this);";
if (e.Item.ItemType == ListItemType.SelectedItem)
{
e.Item.CssClass = string.Format("{0} {1}", e.Item.CssClass, DataGridSelectedRowCssClass);
}
}
}
}
I have a HyperLinkField which I populate with the urls from a datatable, the field in the datatable is called EncodedAbsUrl.
However, I want to connect this link to a code behind method instead
What I do now
var encodedAbsUrl = new string[] { "EncodedAbsUrl" };
var hf = new HyperLinkField
{
HeaderText = "Link",
DataTextField = "ServerUrl",
DataNavigateUrlFields = encodedAbsUrl,
DataNavigateUrlFormatString = "{0}",
Target = "_blank",
};
But id like to do something like this
var encodedAbsUrl = new string[] { "EncodedAbsUrl" };
var hf = new HyperLinkField
{
HeaderText = "Link",
DataTextField = "ServerUrl",
NavigateUrl = clicker(encodedAbsUrl["{0}"]),
Target = "_blank",
};
protected void clicker(string url)
{
//...
}
Well you can see my attempts are unsuccessful :)
Any advice is appreciated
Thanks!
if you will use HyperLinkField so you will not need to Clicker or any postback event because this field will be rendered as <a> tag. I made a sample example using HyperLink control and LinkButton control that will be postback your page.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gv.DataSource = [YourDataSource];
gv.DataBind();
}
}
protected void Clicker(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Link")
{
Response.Redirect(e.CommandArgument.ToString());
}
}
protected void gv_DataBinding(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hlink = e.Row.FindControl("hlink") as HyperLink;
hlink.NavigateUrl = ((Person)e.Row.DataItem).NavUrl;
hlink.Text = ((Person)e.Row.DataItem).NavUrl;
hlink.Target = "_blank";
LinkButton lnkButton = e.Row.FindControl("lnkButton") as LinkButton;
lnkButton.Text = ((Person)e.Row.DataItem).NavUrl;
lnkButton.CommandName = "Link";
lnkButton.CommandArgument = ((Person)e.Row.DataItem).NavUrl;
}
}
you GridView will like this
<asp:GridView runat="server" ID="gv" OnRowCommand="Clicker" OnRowDataBound="gv_DataBinding"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink runat="server" ID="hlink"></asp:HyperLink>
<asp:LinkButton runat="server" ID="lnkButton"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You'll need to use a LinkButton if you want to be able to postback to the server in the way you require.
This class has an OnClick event unlike the HyperLinkField you've been using.
You can find out more info about the LinkButton class here.