Simultaneously deleting a file from a DataBase and a Folder using a LinkButton or Gridview_RowDeleting method - asp.net

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>

Related

Data binding along with the value in ASP.NET

How do you achive something like below in asp.net?
<asp:Label runat="server" Text="The '<%# CustomValue %>' you assigned."/>
This usually depends on where your Label resides. If it is a stond alone control, not nested inside a repeater, you just set your code in code behind:
Label1.Text = $"The {CustomValue} you assigned.";
If the label is nested inside an ItemTemplate in some sort of Repeater control, you can strongly type it to an objects property:
<asp:Repeater runat="server" ID="MyRepeater" ItemType="WebFormsSandbox.Person">
<ItemTemplate>
<li>
<%#: Item.FirstName %> <%#: Item.LastName %>
</li>
</ItemTemplate>
</asp:Repeater>
and the corresponding code behind:
protected void Page_Load(object sender, EventArgs e)
{
MyRepeater.DataSource = Persons();
MyRepeater.DataBind();
}
IEnumerable<Person> Persons()
{
for (int i = 0; i < 10; i++)
{
yield return new Person { Id= i, FirstName = $"Foo{i}", LastName = $"Bar{i}" };
}
}
This would create a list of links, where you then could do anything with it. Whether this would pop up a custom window or does a postback .. up to you.
If you really want to do it that way, write the string inside the server tags.
<asp:Label runat="server" Text='<%# "The " + CustomValue + " you assigned." %>'/>
However if the Label is not inside a GridView, Repeater etc you have to call DataBind manually.
protected void Page_Load(object sender, EventArgs e)
{
DataBind();
}
You would typically do this in the code behind on page load, unless you were using a datagrid or repeater control. Assign an ID to your control and reference it like so.
<asp:Label runat="server" ID="Label1" />
protected void Page_Load(object sender,EventArgs e)
{
Label1.Text = "Your Value";
}

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;

Updated By column in Gridview

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;
}

Passing a variable from aspx to .cs

I am trying to pass an Id from aspx to .cs. This is the code i have in the aspx:
<asp:Button ID="btnAddAsFriend" runat="server" Text="Add as Friend" onclick="btnAddAsFriend_Click" CommandName = "Id" CommandArgument='<%# Eval("u.UserID.ToString()") %>'/>
The CommandArgument is being set but when i try to read it from the .cs its getting null. This is the code I have in the .cs
protected void btnAddAsFriend_Click(object sender, EventArgs e)
{
string id = ((Button)sender).CommandArgument;
}
Thanks

Resources