Updated By column in Gridview - asp.net

I have a grid view which is bound to an ObjectDataSource. After users have finished updating their data, I would like to put their username or userid in the UpdatedBy column to keep track who has updated what record. The UpdatedBy column could be hidden or readonly on the page so users can't just put any text in there.
Here is my UpdatedBy field:
<asp:BoundField DataField="UpdatedBy" HeaderText="Updated By" SortExpression="UpdatedBy" />
<asp:TemplateField HeaderText="Updated By">
<asp:itemTemplate>
<asp:Label ID="lblUpdatedBy" runat="server" Text='<% #Eval("UpdatedBy") %>' Width="30" ></asp:Label>
</asp:itemTemplate>
<asp:editItemTemplate>
<asp:TextBox ID="txtUpdatedBy" runat="server" CssClass="Gridview_EditItem" Text='<% #Bind("UpdatedBy") %>' Width="30" ></asp:TextBox>
</asp:editItemTemplate>
</asp:TemplateField>
I put updating code in RowUpdating event, but for some reason it doesn't work.
protected void gvProductQuery_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow gr = gvProductQuery.Rows[e.RowIndex];
TextBox tb = gr.FindControl("txtUpdatedBy") as TextBox;
tb.Text = cUser.DomainLogin;
}
The tb is Null in the above code. Please help. Or is there an easier way to do this? I'm using VS2012
Thanks

try this out :
protected void gvProductQuery_RowEditing(object sender, GridViewEditEventArgs e)
{
gvProductQuery.EditIndex = e.NewEditIndex;
gvProductQuery.DataBind();
}
protected void gvProductQuery_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gvProductQuery.Rows[gvLevels.EditIndex];
TextBox tb = row.FindControl("txtUpdatedBy") as TextBox;
tb.Text = cUser.DomainLogin;
}

Related

Simultaneously deleting a file from a DataBase and a Folder using a LinkButton or Gridview_RowDeleting method

HELP! Is it achievable to use LinkButton or Gridview_RowDeleting method to simultaneously delete a file from a DataBase and from a Folder? Below is my code using a LinkButton:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID = "lnkDelete" Text = "Delete" OnClientClick="return confirm('Are you sure you want to delete this record?');" CommandArgument = '<%# DataBinder.Eval(Container.DataItem,"ID") %>' runat = "server" OnClick = "DeleteFile" />
</ItemTemplate>
</asp:TemplateField>
Code Behind:
protected void grdProducts_RowEditing(object sender, GridViewEditEventArgs e)
{
//Get seleted row
GridViewRow row = grdProducts.Rows[e.NewEditIndex];
//Get Id of selected product
int rowId = Convert.ToInt32(row.Cells[1].Text);
//Redirect user to Manage Products along with the selected rowId
Response.Redirect("~/Pages/Management/ManageProducts.aspx?id=" + rowId);
}
protected void DeleteFile(object sender, EventArgs e)
{
string filePath = (sender as LinkButton).CommandArgument;
File.Delete(filePath);
Response.Redirect(Request.Url.AbsoluteUri);
}
PL: I have an existing gridview and a datasource for my table.
Thank you all for your contribution. I later got the answer to this. I will like to share it with all. Just enable OnRowDeleting in your Gridview properties then use the code behind below.
protected void grdProducts_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Image oImg = grdProducts.Rows[e.RowIndex].FindControl("ImageFile") as Image;
if (oImg != null)
{
string sUrl = oImg.ImageUrl;
File.Delete(Server.MapPath(sUrl));
grdProducts.DataBind();
}
}
}
Finally: put this TemplateField on your aspx page.
<asp:TemplateField>
<ItemTemplate>
<asp:Image ID="ImageFile" runat="server" ImageUrl='<%# Bind("Image", "Images/Products/{0}")%>' AlternateText="Picture unavailable" style="width:50px; height:40px" />
</ItemTemplate>
</asp:TemplateField>

ASP.NET - Finding Label Control in a GridView

I'm having a problem trying to find a label control that is inside a GridView.
Please see my codes below:
<asp:GridView ID="MyGridView" runat="server">
<Columns>
<asp:TemplateField HeaderText="Date">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtDate" MaxLength="10" Width="70" />
<asp:ImageButton ID="imgScoreDate" runat="server" ImageUrl="~/images/calendar.gif" />
<ajaxtoolkit:CalendarExtender ID="txtDate_CalendarExtender" runat="server" Enabled="True" Format="MM/dd/yyyy" TargetControlID="txtDate" PopupButtonID="imgDate" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And here is my .cs file:
protected void LoadGridView()
{
//Do something else
foreach (GridViewRow row in MyGridView.Rows)
{
//Tried A
System.Web.UI.WebControls.Label lblName = row.FindControl("lblName") as System.Web.UI.WebControls.Label;
lblName.Text = "Name";
//Tried B
((System.Web.UI.WebControls.Label)row.FindControl("lblName")).Text = "Name";
}
}
I debug this code and it seems to work fine because my breakpoint is being hit each time the debugger runs. It even loops through my foreach block the same count as to how many rows my GridView has.
But I don't understand why my lblName control doesn't get the "Name" text as a value? Am I missing anything here? I tried both //Tried A and //Tried B methods but they both doesn't update my label's text.
Any help would be appreciated!
Thanks! Cheers!
You want to call LoadGridView inside PreRender. Basically, you want to call it after GridView is bound with data.
protected void Page_PreRender(object sender, EventArgs e)
{
LoadGridView();
}
Look at PreRender event of ASP.NET Page Life Cycle.
On your gridview add:
<asp:GridView OnRowDataBound="MyGridView_RowDataBound" ... />
Then define MyGridView_RowDataBound:
void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
Label l = (Label) e.Row.FindControl("lblName");
}
What I think is happening is the control is not recreated server side in its current spot.
try this
on .aspx page
<asp:GridView ID="MyGridView" runat="server"
onrowdatabound="MyGridView_RowDataBound" .../>
code behind ::
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadGridView();
}
}
void LoadGridView()
{
DataTable dt = new DataTable();
// dt= call ur database method to get data
MyGridView.DataSource = dt;
MyGridView.DataBind();
}
protected void MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbl_Name = (Label)e.Row.FindControl("lblName");
lbl_Name.Text = "Name";
}
}
cheers!

Getting row from hyperlink in Gridview

I have a Hyperlink field in a asp.net gridview that runs code behind in an aspx file, like
<asp:GridView ID="gvCoursesList" runat="server">
<Columns>
<asp:BoundField DataField="Course" HeaderText="Course">
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lblSignup" runat="server" Text="Sign Up" OnClick= "lblSignup_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In my code behind file I have the function:
protected void lblSignup_Click(object sender, EventArgs e)
{
}
How do I retrieve the value of the first column from this function.
I would like to do something like
string course = gvCoursesList.DataKeys[e.RowIndex].Value.ToString();
but it's not working. Any other ideas?
#jishnusaha should be the approach you should take. Here is another alternative: http://forums.asp.net/p/1137287/1821091.aspx
protected void lblSignup_Click(object sender, EventArgs e)
{
LinkButton btn = sender as LinkButton;
GridViewRow row = btn.NamingContainer as GridViewRow;
string course = gvCoursesList.DataKeys[row.RowIndex].Value.ToString();
}
<asp:GridView ID="gvCoursesList" runat="server" OnRowCommand="gvCoursesList_RowCommand">
<Columns>
<asp:BoundField DataField="Course" HeaderText="Course">
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lblSignup" runat="server" Text="Sign Up" CommandName="SignUp" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
protected void gvCoursesList_RowCommand(object sender, GridViewRowCommandEventArgs e)
{
if(e.CommandName=="SignUp")
{
string course = gvCoursesList.DataKeys[e.RowIndex].Value.ToString();
}
}
Use the .cells.text to get the value out:
protected void lblSignup_Click(object sender, EventArgs e)
{
GridViewRow row = gvCoursesList.rows[e.rowindex]
string course = row.cells[cellIndex].text;
}
With thanks to codingbiz. His solution just needed a little tweak as per below.
LinkButton btn = sender as LinkButton;
GridViewRow row = btn.NamingContainer as GridViewRow;
string course = row.Cells[0].Text;

Linkbutton click in a asp:GridView cell does not trigger OnRowCommand event

UI Feature: I have a GridView with few columns. Most important column is PcCode, which shows a string value for each row.
Expected: When I click on one of the cell from a row of that PcCode column another GridView should be displayed. However, when I am trying to use a asp:LinkButton for a cell, things just don't work. RowCommand does not get triggered when I click on a asp:LinkButton in the GridView cell. Where am I doing things wrong? Which way the expected functionality can be achieved? Thanks in advance for helping out a newbie.
In the following code I was trying to get a RowIndex and pass it through the CommandArgument and use a CommandName.
.aspx code
<asp:GridView ID="_UIProfitcenterTotalGridView" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" AllowPaging="True" PageSize="22" ShowFooter="True" AutoGenerateColumns="False"
DataKeyNames="ProfitcenterCode" EnableViewState="False"
OnRowDataBound="_UIProfitcenterTotalGridView_RowDataBound"
OnPageIndexChanging="_UIProfitcenterTotalGridView_PageIndexChanging"
OnRowCommand="_UIProfitcenterTotalGridView_OnRowCommand">
<Columns>
<asp:TemplateField HeaderText="PcCode" InsertVisible="False"
ShowHeader="False" SortExpression="ProfitcenterCode" FooterText="Total" FooterStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:LinkButton ID="_UIPCCodeLinkButton" runat="server" Text='<%# Eval("ProfitcenterCode") %>'
CommandName="Select"
CommandArgument='<%# ((GridViewRow) Container).RowIndex %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
...
code behind for aspx.cs
protected void _UIProfitcenterTotalGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = _UIProfitcenterTotalGridView.Rows[index];
string ProfitcenterCode = _UIProfitcenterTotalGridView.DataKeys[_UIProfitcenterTotalGridView.SelectedIndex].Values["ProfitcenterCode"].ToString();
}
}
After the row is selected I need to take the selected row's value as a string and compare with a listitem to show a new GridView.
Tried
Using Link_Button_Click(Object sender, EventArgs e) and the following but failed.
protected void _UIProfitcenterTotalGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{string ProfitcenterCode = ((GridViewRow)(((LinkButton)e.CommandSource).NamingContainer)).Cells[2].Text;
}
}
I tried to use LinkButton_Click() event instead of RowCommand as jason suggested:
protected void LinkButton_Click(Object sender, EventArgs e)
{
LinkButton button = (LinkButton)sender;
GridViewRow row = (GridViewRow)button.NamingContainer;
if (row != null)
{
string theValue = ((LinkButton)sender).CommandArgument.ToString();
...
...
//code for the extra thing I needed to do after selecting a cell value.
}
}
However I still had the problem, which I figured out. The problem was the LinkButton was not binding to the rows thefore, it could not pass any value on selection. What was missing was the following code:
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton linkButton = new LinkButton();
linkButton.Text = e.Row.Cells[0].Text; //value of the first column from the grid
linkButton.Enabled = true;
linkButton.Click += new EventHandler(LinkButton_Click); //triggering the LinkButton event here.
e.Row.Cells[0].Controls.Add(linkButton);
}
You can use the sender object ( the link button that calls the event) and get the parent row from the gridview. Example:
Protected Sub linkButton_click(ByVal sender As Object, ByVal e As EventArgs)
'First cast the sender to a link button
Dim btn As LinkButton = CType(sender, LinkButton)
'now, if there is a command arguement, you can get that like this
Dim id As String = btn.CommandArgument
'to get the gridviewrow that the button is on:
Dim row As GridViewRow = CType(btn.NamingContainer, GridViewRow)
End Sub
It was hard to follow exactly what you were looking for, so if i missed something let me know and I will add it.
protected void linkButton_click(object sender, EventArgs e)
{
//First cast the sender to a link button
LinkButton btn = (LinkButton)sender;
//now, if there is a command arguement, you can get that like this
string id = btn.CommandArgument;
//to get the gridviewrow that the button is on:
GridViewRow row = (GridViewRow)btn.NamingContainer;
}
And change your linkbutton to:
<asp:LinkButton OnClick="linkButton_click" ID="_UIPCCodeLinkButton"
runat="server" Text='<%# Eval("ProfitcenterCode") %>'
CommandName="Select"
CommandArgument='<%# ((GridViewRow) Container).RowIndex %>'>

gridview edit requires to click twice

Why is that I need to click the edit link twice, in a gridview control, before my row enters into edit mode?
<asp:ObjectDataSource ID="ods" runat="server" TypeName="Employee"
SelectMethod="GetAll" ></asp:ObjectDataSource>
<asp:GridView ID="GridView1" runat="server" CssClass="styled"
OnRowCommand="gv_RowCommand" DataSourceID="ods"
OnSorting="gv_Sorting" >
<Columns>
...........
</Columns>
<ItemTemplate>
<ItemTemplate>
<div class='actions'>
<asp:Button ID="btnEdit" runat="server" Text=" Edit " ToolTip="Edit Row" CommandName="Edit" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"Id") %>' CausesValidation="False" />
<span style="padding-left:10px"></span>
</div>
</ItemTemplate>
</asp:GridView>
protected override void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.ods.SelectParameters[0].DefaultValue = "";
}
}
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == CRUID.Edit.ToString())
{
this.gv.ShowFooter = false;
}
}
You need to avoid rebinding your gridview on each postback.
If not ispostback then
GridView1.DataSource = dt
GridView1.DataBind()
end if
Otherwise you just overwrite Gridview changes.
Great explanation at this link...
http://www.pcreview.co.uk/forums/gridview-two-clicks-needed-enter-place-editing-t3328887.html
Try handling the RowEditing event to set the EditItem Index:
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
gv.EditIndex = e.NewEditIndex
}
There are some mistakes in your code as i examined. Correct your code as shown below:
<asp:ObjectDataSource ID="ods" runat="server" TypeName="Employee"
SelectMethod="GetAll" ></asp:ObjectDataSource>
<asp:GridView ID="GridView1" runat="server" CssClass="styled"
OnRowCommand="gv_RowCommand" DataSourceID="ods"
OnSorting="gv_Sorting" >
<Columns>
...........
<asp:TemplateField>
<ItemTemplate>
<div class='actions'>
<asp:Button ID="btnEdit" runat="server" Text=" Edit " ToolTip="Edit Row" CommandName="Edit" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"Id") %>' CausesValidation="False" />
<span style="padding-left:10px"></span>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected override void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.ods.SelectParameters[0].DefaultValue = "";
}
}
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
this.gv.ShowFooter = false;
}
}
If on using this code the problem does not solve then there may be some problem in your cssclass which you used with your GridView as I have Checked your code on my machine using ObjectDataSource and it works well using edited code.
Also I want to know that what is CRUID in CRUID.Edit.ToString()
and why you used the following line in Page_Load event
this.ods.SelectParameters[0].DefaultValue = "";
as there are no parameter associated with your SelectMethod="GetAll" method used in ObjectDataSource.
May this answer help you.
I guess there is some conflict with the updatepanels on your page..
Try removing all your Update Panels and try again.. It will work for sure.. Mine worked a few seconds ago.. so thought It would be good to share..

Resources