Hy,
I have a gridView control in Asp.NET like this:
<asp:GridView ID="outputGridView" runat="server" onrowediting="OutputGridView_RowEditing">
<asp:TemplateField ItemStyle-HorizontalAlign="Left" ItemStyle-VerticalAlign="Middle"
ItemStyle-Width="250px" HeaderText="JobId" HeaderStyle-HorizontalAlign="Left"
HeaderStyle-BorderWidth="1px" HeaderStyle-BorderColor="#e1e1e1">
<ItemTemplate>
<%# Eval("JobId")%>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" VerticalAlign="Middle" Font-Bold="True"></HeaderStyle>
<ItemStyle HorizontalAlign="Left" VerticalAlign="Middle" Width="250px" BorderWidth="1px"
BorderColor="#e1e1e1"></ItemStyle>
</asp:TemplateField>
</aspGridView>
On OutputGridView_RowEditing I have this code:
protected void OutputGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewRow currentRow = outputGridView.Rows[e.NewEditIndex];
string JobId = currentRow.Cells[2].Text;
e.Cancel = true;
}
But in 'JobId' string its "", does anyone have any idea how can I get the text of the third cell from the row that is being edited?
Thank you,
Jeff
Ok what Bonshington said is correct, accept you want to add an id to the label.
<ItemTemplate>
<asp:Label ID="LblJobId" runat="server" Text='<%# Eval("JobId") %>' />
</ItemTemplate>
protected void OutputGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewRow currentRow = outputGridView.Rows[e.NewEditIndex];
Label jobIdLabel = (Label)currentRow.Cells[2].FindControl("LblJobId");
string jobId = jobIdLabel.Text;
e.Cancel = true;
}
Please use Bind() method instead of Eval() method, it is for evaluation purpose only.
try to put it in literal cotnrol
<label><%# Eval("JobId")%></label>
and your jobID column will positioned as cell's child control
if you want to get GridViewRow currentRow you have to use
<Columns>
<asp:TemplateField>
<EditItemTemplate><asp:Label id="lbl" Text="<%# Eval("JobId")%>" /></EditItemTemplate>
</asp:TemplateField>
</Columns>
Auto-generated grid columns use Cells property
protected void OutputGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
OutputGridView.Rows[e.NewEditIndex].Cells[0]
}
Related
I Have a GridView which conntains multiple records and couple of Link Buttons Named Edit and Detail. Now i want to Get the Name of the User (NOT Index), when a user click on Detail Link Button. Like "Name", "FatherName" etc
Here is the .aspx code
<asp:GridView ID="dgvEmployeesInformation" runat="server" CssClass=" table table-bordered table-hover table-responsive" DataKeyNames="Id" AutoGenerateColumns="False" OnRowCommand="dgvEmployeesInformation_RowCommand" OnRowDataBound="dgvEmployeesInformation_RowDataBound" AllowPaging="True" AllowSorting="True" OnPageIndexChanging="dgvEmployeesInformation_PageIndexChanging">
<%--1st Column--%>
<Columns>
<asp:BoundField HeaderText="ID" DataField="Id" ControlStyle-BackColor="#0066ff" Visible="False">
<ControlStyle BackColor="#0066FF"></ControlStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="Employee No" DataField="EmployeeNo" />
<asp:BoundField HeaderText="Father Name" DataField="FatherName" />
<asp:HyperLinkField DataNavigateUrlFields="Id" DataNavigateUrlFormatString="AddEmployeeBasic1.aspx?thid={0}" HeaderText="Update" NavigateUrl="~/AddEmployeeBasic1.aspx" Text="Edit" />
<asp:TemplateField HeaderText="Action" ShowHeader="True">
<ItemTemplate>
<asp:LinkButton ID="lbDelete" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="lbDetail" OnClick="lbDetail_Click" DataNavigateUrlFields="Id" DataNavigateUrlFormatString="EmployeesDetails.aspx?EmpID={0}" NavigateUrl="~/EmployeesDetails.aspx" HeaderText="Show Detail" Text="Detail"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is the lbDetail_Click Code
protected void lbDetail_Click(object sender, EventArgs e)
{
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
Label lblUserName = (Label)clickedRow.FindControl("Name");
EmployeeID.EmpName = lblUserName.ToString();
}
When i put my program on Debugging mode, the lblUserName return NULL
Here is the picture.
What i want is that, when a user click on Detail LinkButton, then on lbDetail Click event, it gets the Name of the Employee and store it in a static variable. Following is the picture
I don't understand how to solve this problem. Please help me through this. Your help will be really appreciated.
I would just add data attributes to the details button then get it's values at code behind.
For example:
1.) Add new data-myData='<%# Eval("Name") %>' attribute and its value to button
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="lbDetail" OnClick="lbDetail_Click" Text="Detail" data-ID='<%# Eval("ID") %>' data-myData='<%# Eval("Name") %>' ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
2.) Get those data from event handler
protected void lbDetail_Click(object sender, EventArgs e)
{
LinkButton button = (LinkButton)sender;
var name = (string)button.Attributes["data-myData"];
var selectedID = (string)button.Attributes["data-ID"];
Session["selectedID"] = selectedID ;
}
lblUserName is null because it's not a Label, but a BoundField.
What you could do it get the Cell value.
protected void lbDetail_Click(object sender, EventArgs e)
{
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
Label1.Text = clickedRow.Cells[1].Text;
}
Or use a TemplateField that does contain a Label Name
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="Name" runat="server" Text='<%# Eval("Name")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Here is how your code should look:
protected void lbDetail_Click(object sender, EventArgs e)
{
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
var username = clickedRow.Cells[1].Text;
if(string.IsNullOrEmpty(username))
{
return;
}
EmployeeID.EmpName = username;
}
This is my markup:-
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
Width="245px" onrowcommand="GridView1_RowCommand" >
<Columns>
<asp:TemplateField>
<ItemStyle BackColor="#CCCCCC" ForeColor="Black" Width="250px" HorizontalAlign="Center"
BorderStyle="None" />
<ItemTemplate>
<asp:LinkButton ID="userList" runat="server" CommandName="Select" CommandArgument ='<%# Container.DataItemIndex %>' Text='<%# Bind("users") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And in the codebehind, I am trying to get the current row's text value, but can't seem to get it;
it returns "".
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int rowValue = Convert.ToInt32(e.CommandArgument.ToString());
GridView1.SelectedIndex = rowValue;
string test = GridView1.SelectedRow.Cells[0].Text;
}
You need to find and acces the control
LinkButton btn = (LinkButton)gvDealerSupportMail.Rows[rowValue].FindControl("userList");
string result = btn.Text;
you can use CommandSource to get the Command.Text, CommandName and CommandArgument.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
LinkButton commandSource = e.CommandSource as LinkButton;
string commandText = commandSource.Text;
string commandName = commandSource.CommandName;
int commandArgument = Convert.ToInt32(commandSource.CommandArgument);
}
I have a link button inside a gridView as below :
<asp:TemplateField HeaderText="Analyze">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" Text="Analyze" runat="server" OnClick="LinkButton1_Click" />
</ItemTemplate>
</asp:TemplateField>
I have the LinkButton1_Click function as below :
protected void LinkButton1_Click(object sender, EventArgs e)
{
testtb.Text = name;
Console.WriteLine(name);
}
This variable "name" is the first column of the GridView.I am obtaining the value for "name" as below:
protected void UnanalysedGV_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView d = (DataRowView)e.Row.DataItem;
name = d["resultId"].ToString();
}
}
I want that on click of the link button the value of first column in that row of gridview becomes the text for the textbox testtb.
Somehow,the value for name remains null.
EDIT
I found out that probably RowDataBound isn't the correct event for my requirements because I need the value for each row.
So I removed the RowDataBound function.
I guess I have to handle this inside LinkButton1_Click itself.
I added this line to the function :
name = UnanalysedGV.SelectedRow.Cells[1].Text;
Still doesn't work.
Does anyone have any idea ?
You can do it using two approaches as mentioned below.
Handle click event of linkbutton through event bubbling code -
<asp:GridView AutoGenerateColumns="false" runat="server" ID="grdCustomPagging" OnRowCommand="grdCustomPagging_RowCommand">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="RowNumber" />
<asp:BoundField DataField="DealId" HeaderText="DealID" />
<asp:BoundField DataField="Dealtitle" HeaderText="DealTitle" />
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkView" CommandArgument='<%#Eval("DealId") %>'
CommandName="VIEW">View Deal</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void grdCustomPagging_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "VIEW")
{
LinkButton lnkView = (LinkButton)e.CommandSource;
string dealId = lnkView.CommandArgument;
}
}
Handle click event of linkbutton directly click event code -
<asp:GridView AutoGenerateColumns="false" runat="server" ID="grdCustomPagging">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="RowNumber" />
<asp:BoundField DataField="DealId" HeaderText="DealID" />
<asp:BoundField DataField="Dealtitle" HeaderText="DealTitle" />
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkView" OnClick="lnkView_Click">View Deal</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void lnkView_Click(object sender, EventArgs e)
{
GridViewRow grdrow = (GridViewRow)((LinkButton)sender).NamingContainer;
string rowNumber = grdrow.Cells[0].Text;
string dealId = grdrow.Cells[1].Text;
string dealTitle = grdrow.Cells[2].Text;
}
Hope this helps.
I am trying to update a value in my gridview on row updating. However, it refuses to take in the value written in the textbox. I populate the gridview if the page is not post back. Help!
GRIDVIEW:
<asp:UpdatePanel runat="server" UpdateMode=Conditional><ContentTemplate>
<asp:GridView runat="server" ID="searchGV" AutoGenerateColumns="False" GridLines="None"
CssClass="mGrid" EmptyDataText="The Search Did Not Return Any Results"
PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt" Width="100%" OnRowCancelingEdit="searchGV_RowCancelingEdit"
OnRowEditing="searchGV_RowEditing" DataKeyNames="media_id" OnRowUpdating="searchGV_RowUpdating">
<Columns>
<asp:BoundField DataField="media_id" Visible="false" HeaderText="" />
<asp:BoundField DataField="dir_path" Visible="false" HeaderText="Dir" />
<asp:TemplateField HeaderText="Date Taken" >
<ItemTemplate>
<asp:LinkButton ID="dateLinkCsBtn" OnClientClick='<%#Eval("dir_path","Javascript:return test(\"{0}\",event);")%>'
runat="server" Text='<%# Bind("date") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Media Type">
<ItemTemplate>
<asp:Label runat="server" ID="mediaTypeLbl" Text='<%#Eval("description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Alias File Name">
<ItemTemplate>
<asp:Label runat="server" ID="aliasFileName" Text='<%#Bind("alias_file_name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" Text='<%#Bind("alias_file_name") %>' ID="updateAliasTxt"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
</ContentTemplate></asp:UpdatePanel>
CODE BEHIND:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillGrid();
}
}
protected void searchGV_RowEditing(object sender, GridViewEditEventArgs e)
{
searchGV.EditIndex = e.NewEditIndex;
FillGrid();
}
protected void searchGV_RowCancelingEdit(object sender,
GridViewCancelEditEventArgs e)
{
searchGV.EditIndex = -1;
FillGrid();
}
public void FillGrid()
{
Media_DAO media_query = new Media_DAO();
searchGV.DataSource = media_query.get_search_media(alias_file_name_txt.Text.Trim(), Convert.ToInt16(mediaTypeDDL.SelectedValue),
from_date_txt.Text.Trim(), to_date_txt.Text.Trim(), Convert.ToInt16(Session["user_id"]));
searchGV.DataBind();
}
protected void searchGV_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = searchGV.Rows[e.RowIndex];
TextBox new_alias = (TextBox)searchGV.Rows[e.RowIndex].FindControl("updateAliasTxt");
int media_id = Convert.ToInt16(searchGV.DataKeys[e.RowIndex]["media_id"]);
Media_DAO media_query2 = new Media_DAO();
media_query2.update_alias_name_by_id(media_id, new_alias.Text.Trim(), Convert.ToInt16(Session["user_id"]));
searchGV.EditIndex = -1;
FillGrid();
}
while declaring the grid you have specified only 1 *data key value*
asDataKeyNames="media_id"
DateKeys for grid view is stored in array format starting from 0.
The error may be in getting the media_id while updating. You need to change it as follows.
protected void searchGV_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = searchGV.Rows[e.RowIndex];
TextBox new_alias = (TextBox)searchGV.Rows[e.RowIndex].FindControl("updateAliasTxt");
int media_id = Convert.ToInt16(e.Keys[0]); //this will get the media_id
Media_DAO media_query2 = new Media_DAO();
media_query2.update_alias_name_by_id(media_id, new_alias.Text.Trim(), Convert.ToInt16(Session["user_id"]));
searchGV.EditIndex = -1;
FillGrid();
}
Since the earlier method was searchGV.DataKeys[e.RowIndex]["media_id"] , you might not get the media_id value if the row number which you are trying to edit is greater than 1.
The DataKeys property of GridView returns a collection of DataKey objects that represents the data key value of each row for a GridView. Thus, DataKeys[1] gives 2nd row, DataKeys[4] gives 5th row ...
Therefore, you need to use either the Value OR the Values property to access the value of a key field.
Rather than doing this:
int media_id = Convert.ToInt16(searchGV.DataKeys[e.RowIndex]["media_id"]);
do this:
int media_id = Convert.ToInt16(searchGV.DataKeys[e.RowIndex].Values["media_id"]);
// You can also use the Value property which gives the key value at index 0
int media_id = Convert.ToInt16(searchGV.DataKeys[e.RowIndex].Value);
<asp:GridView ID="gvGrid" runat="server" AutoGenerateColumns="False"
DataSourceID="dsDataSource" AllowPaging="True" PageSize="20" >
<Columns>
<asp:BoundField DataField="Field1" HeaderText="Field1"
SortExpression="Field1" />
<asp:BoundField DataField="Field2" HeaderText="Field2"
SortExpression="Field2" />
<asp:TemplateField HeaderText="TemplateField1">
<ItemTemplate>
<asp:Label id="lblComments" runat="server" Text=" i use a function to compute"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowSelectButton="True" SelectText="Complete" HeaderText ="Status" />
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="btnComplete" runat="server" Text="Complete" onclick="btnComplete_Click"/>
<asp:Button ID="btnAddComment" runat="server" Text="Add Comment" onclick="btnAddComment_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void btnComplete_Click(object sender, EventArgs e)
{
String Field1 = gvGrid.SelectedRow.Cells[1].Text; // throws an error at runtime
//I want to be able to access the row data do some computation and then be able to insert it into the database
// Reason why I am trying to use it as a template field instead of a commandfield is because I want to make it not visible when it meets certain condition.
}
Also, it would be great if you could let me know a better way to do it, maybe using the command field and if there is a way to toggle its visibility. I don't mind using LinkButton either.
You can do it like this:
protected void btnComplete_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
GridViewRow gvRow = (GridViewRow)btn.Parent.Parent;
//Alternatively you could use NamingContainer
//GridViewRow gvRow = (GridViewRow)btn.NamingContainer;
Label lblComments = (Label)gvRow.FindControl("lblComments");
// lblComments.Text ...whatever you wanted to do
}
here is how you can access to the gridview row:
protected void btnComplete_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gvGrid.Rows)
{
Label lblComments = row.FindControl("lblComments") as Label;
....//you can do rest of the templatefiled....
}
}