Upload files in Gridview and display in the same row upon completion - c#

I am trying to store files from a Gridview upload into a Folder using Asp.net.
This is my markup code to generate Upload column and The button and File Upload control.
<asp:TemplateField HeaderText="Upload">
<ItemTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" EnableViewState="true" AllowMultiple="true" />
<asp:Button ID="btnUpload" runat="server" CommandName="Upload" Text="OK" style=" color: #ff0000" OnClick="btnUpload_Click"/>
</ItemTemplate>
</asp:TemplateField>
I have my codebehind to handle btnUpload_Click as below:
protected void btnUpload_Click(object sender, GridViewCommandEventArgs e)
{
Response.Write("File has been passed");
Button bts = e.CommandSource as Button;
Response.Write(bts.Parent.Parent.GetType().ToString());
if (e.CommandName.ToLower() != "upload")
{
return;
}
FileUpload fu = bts.FindControl("FileUpload4") as FileUpload;//here
if (fu.HasFile)
{
bool upload = true;
string fleUpload = Path.GetExtension(fu.FileName.ToString());
if (fleUpload.Trim().ToLower() == ".xls" | fleUpload.Trim().ToLower() == ".xlsx")
{
fu.SaveAs(Server.MapPath("~/UpLoadPath/" + fu.FileName.ToString()));
string uploadedFile = (Server.MapPath("~/UpLoadPath/" + fu.FileName.ToString()));
//Someting to do?...
}
else
{
upload = false;
// Something to do?...
}
if (upload)
{
// somthing to do?...
}
}
else
{
//Something to do?...
}
}
I am getting this error:
CS0123: No overload for 'btnUpload_Click' matches delegate
'System.EventHandl
Can somebody please help me?

You're binding both Command and Click event with your button. Your button code should be like this-
<asp:TemplateField HeaderText="Upload">
<ItemTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" EnableViewState="true" AllowMultiple="true" />
<asp:Button ID="btnUpload" runat="server" CommandName="Upload" Text="OK" style=" color: #ff0000"/>
</ItemTemplate>
</asp:TemplateField>
and from code behind capture the command not the event. like-
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
Response.Write("File has been passed");
Button bts = e.CommandSource as Button;
Response.Write(bts.Parent.Parent.GetType().ToString());
if (e.CommandName.ToLower() != "upload")
{
return;
}
FileUpload fu = bts.FindControl("FileUpload1") as FileUpload;//here
if (fu.HasFile)
{
bool upload = true;
string fileName = Path.GetFileName(fu.PostedFile.FileName);
string fleUpload = Path.GetExtension(fu.PostedFile.FileName);
if (fleUpload.Trim().ToLower() == ".xls" || fleUpload.Trim().ToLower() == ".xlsx")
{
fu.SaveAs(Server.MapPath("~/UpLoadPath/" + fileName));
string uploadedFile = (Server.MapPath("~/UpLoadPath/" + fileName ));
//Someting to do?...
}
else
{
upload = false;
// Something to do?...
}
if (upload)
{
// somthing to do?...
}
}
else
{
//Something to do?...
}
}
above I'm assuming your gridview ID is GridView1. And another one your File Uploader control's ID was mismatched with your code behind. This should work.

Related

How to set 3 radiobutton with its groupname in a repeater

I need to set 3 different groups of radio button in a repeater. Using groupname property for it wasn't enough. So, after researching, I use a bit of JS and it works. My problem is when I want to implement more than one group of radiobuttons. Can anyone help me?
My best approach is:
CSHTML
<asp:Repeater runat="server" ID="repeaterImages" OnItemDataBound="repeaterImages_ItemDataBound">
<ItemTemplate>
<span>
<asp:RadioButton runat="server" ID="rbLogoSeleccionado" Text='Logo 0' GroupName="nombreLogo" /><br />
<asp:RadioButton runat="server" ID="rbLogoSeleccionadoApp" Text='Logo 1' GroupName="nombreLogoApp" /><br />
<asp:RadioButton runat="server" ID="rbLogoSeleccionadoAppBlanco" Text='Logo 2' GroupName="nombreLogoAppBlanco" />
</span>
</ItemTemplate>
</asp:Repeater>
JS
<script>
function SetUniqueRadioButton(nameregex, current) {
for (i = 0; i < document.forms[0].elements.length; i++) {
elm = document.forms[0].elements[i]
if (elm.type == 'radio') {
elm.checked = false;
}
}
current.checked = true;
}
</script>
CS
protected void repeaterImages_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
RadioButton rbLogoSeleccionado = (RadioButton)e.Item.FindControl("rbLogoSeleccionado");
RadioButton rbLogoSeleccionadoApp = (RadioButton)e.Item.FindControl("rbLogoSeleccionadoApp");
RadioButton rbLogoSeleccionadoAppBlanco = (RadioButton)e.Item.FindControl("rbLogoSeleccionadoAppBlanco");
string script = "SetUniqueRadioButton('repeaterImages.*nombreLogo',this)";
string scriptApp = "SetUniqueRadioButton('repeaterImages.*nombreLogoApp',this)";
string scriptAppBlanco = "SetUniqueRadioButton('repeaterImages.*nombreLogoAppBlanco',this)";
rbLogoSeleccionado.Attributes.Add("onclick", script);
rbLogoSeleccionadoApp.Attributes.Add("onclick", scriptApp);
rbLogoSeleccionadoAppBlanco.Attributes.Add("onclick", scriptAppBlanco);
}
}
catch (Exception ex)
{
PIPEvo.Log.Log.RegistrarError(ex);
throw;
}
}
With this code just getting 3 rows of radiobutton, sharing groupname behavior for all of them... (I want groupname behavior per row...)
Piece of cake. Prove how newie I am in JS. I am posting the solution because is a recurrent issue in asp programming and this bug is known. Beside I cant find the solution for some radio button.
JS.
<script>
function SetUniqueRadioButton(text, current) {
for (i = 0; i < document.forms[0].elements.length; i++) {
elm = document.forms[0].elements[i]
if ((elm.type == 'radio') && (elm.value == text)) {
elm.checked = false;
}
}
current.checked = true;
}
</script>
CS
protected void repeaterImages_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
RadioButton rbLogoSeleccionado = (RadioButton)e.Item.FindControl("rbLogoSeleccionado");
RadioButton rbLogoSeleccionadoApp = (RadioButton)e.Item.FindControl("rbLogoSeleccionadoApp");
RadioButton rbLogoSeleccionadoAppBlanco = (RadioButton)e.Item.FindControl("rbLogoSeleccionadoAppBlanco");
string script = "SetUniqueRadioButton('rbLogoSeleccionado',this)";
string scriptApp = "SetUniqueRadioButton('rbLogoSeleccionadoApp',this)";
string scriptAppBlanco = "SetUniqueRadioButton('rbLogoSeleccionadoAppBlanco',this)";
rbLogoSeleccionado.Attributes.Add("onclick", script);
rbLogoSeleccionadoApp.Attributes.Add("onclick", scriptApp);
rbLogoSeleccionadoAppBlanco.Attributes.Add("onclick", scriptAppBlanco);
}
}
catch (Exception ex)
{
PIPEvo.Log.Log.RegistrarError(ex);
throw;
}
}
CSHTML
<asp:Repeater runat="server" ID="repeaterImages" OnItemDataBound="repeaterImages_ItemDataBound">
<ItemTemplate>
<span>
<asp:RadioButton runat="server" ID="rbLogoSeleccionado" Text='Logo 0' GroupName="nombreLogo" /><br />
<asp:RadioButton runat="server" ID="rbLogoSeleccionadoApp" Text='Logo 1' GroupName="nombreLogoApp" /><br />
<asp:RadioButton runat="server" ID="rbLogoSeleccionadoAppBlanco" Text='Logo 2' GroupName="nombreLogoAppBlanco" />
</span>
</ItemTemplate>
</asp:Repeater>

keep gridview sort after clicking asp linkbutton

I have tried a number of solutions to get this working, but I could not find one that it working for me. I am a beginner at programming in C# with ASP.net, and I would appreciate any help that I can get.
Currently, my gridview allows me to sort, if I click on the column header, and this sorts it by ascending to descending order. However, when I click a link button i.e. one of the buttons in the 'flags' column of my programme, it does highlight that option (it is supposed to do it), but it doesn't keep the sort - I want it to keep the sort after this has been clicked. Would someone be able to help with this please?
Here is my aspx code (this is in asp:GridView):
<%--Flags column--%>
<asp:TemplateField HeaderText ="Flags" ItemStyle-Width="34px" SortExpression="sortFlag">
<ItemTemplate>
<div style="width:34px">
<asp:HiddenField ID="HidSortFlag" Value='<%#Eval("sortFlag") %>' runat="server" />
<asp:HiddenField ID="hidAmended" Value='<%#Eval("Amended") %>' runat="server" />
<asp:HiddenField ID="hidPayAnyway" Value='<%#Eval("PaymentOverrideFlag") %>' runat="server" />
<asp:HiddenField ID="hidQueries" Value='<%#Eval("QueryCount") %>' runat="server" />
<asp:HiddenField ID="hidSupplierRefCount" Value='<%#Eval("SupplierRefCount") %>' runat="server" />
<asp:HiddenField ID="hdnElementRef" Value='<%# Eval("SuggestedMatches") %>' runat="server" />
<asp:LinkButton ID="flagQueries" runat="server" Text="<span class='glyphicon glyphicon-comment' data-toggle='tooltip' data-placement='top' title='Comments and Queries'></span>" OnClick="flagQueries_Click" CommandArgument='<%# Eval("StatementLineId") +";"+Eval("SupplierRef") +";" + Eval("SuggestedMatches")%>' > </asp:LinkButton><br />
<asp:LinkButton ID="flagAmends" runat="server" Text="<span class='glyphicon glyphicon-flag' data-toggle='tooltip' data-placement='top' title='Related Booking Has Been Amended' ></span>" OnClick="flagAmends_Click" CommandArgument='<%# Eval("StatementLineId") %>'></asp:LinkButton><br />
<asp:LinkButton id="flagPayments" runat="server" Text="<span class='glyphicon glyphicon-ok' data-toggle='tooltip' data-placement='top' title='Pay Anyway'></span>" OnClick="flagPayments_Click" CommandArgument='<%# Eval("StatementLineId") + ";" +Eval("SuggestedMatches")%>'></asp:LinkButton> <br />
</div>
</ItemTemplate>
</asp:TemplateField>
Here is the code behind which does the sort:
protected void gridSummary_Sorting(object sender, GridViewSortEventArgs e)
{
//Check if the sort field is being used or a new sort
if (ViewState["summarySortField"] == null)
{
ViewState["summarySortField"] = e.SortExpression;
}
else if (ViewState["summarySortField"].ToString() != e.SortExpression)
{
ViewState["summaryDirectionState"] = null;
ViewState["summarySortField"] = e.SortExpression;
}
summaryDirection = summaryDirection == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending;
string sortingDirection = summaryDirection == SortDirection.Ascending ? "Desc" : "Asc";
DataView summaryView = LoadStatement();
summaryView.Sort = string.Format("{0} {1}", e.SortExpression, sortingDirection);
//Session["SortedView"] = summaryView;
gridSummary.DataSource = summaryView;
gridSummary.DataBind();
//ColourFlags();
}
public SortDirection summaryDirection
{
get
{
if (ViewState["summaryDirectionState"] == null)
{
ViewState["summaryDirectionState"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["summaryDirectionState"];
}
set
{
ViewState["summaryDirectionState"] = value;
}
}
protected void gridDetail_Sorting(object sender, GridViewSortEventArgs e)
{
//Check if the sort field is being used or a new sort
if (ViewState["detailSortField"] == null)
{
ViewState["detailSortField"] = e.SortExpression;
}
else if (ViewState["detailSortField"].ToString() != e.SortExpression)
{
ViewState["detailDirectionState"] = null;
ViewState["detailSortField"] = e.SortExpression;
}
detailDirection = detailDirection == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending;
string sortingDirection = detailDirection == SortDirection.Ascending ? "Desc" : "Asc";
//string gets toggle error field in order to add the colour red to certain columns
DataView detailView = LoadDetails(Session["arg"].ToString());
string[] args = Session["arg"].ToString().Split(';');
string status = args[0];
detailView.Sort = string.Format("{0} {1}", e.SortExpression, sortingDirection);
//Session["SortedView"] = summaryView;
gridDetail.DataSource = detailView;
gridDetail.DataBind();
ColourFlags();
ToggleErrorFields(string.IsNullOrEmpty(status));
}
public SortDirection detailDirection
{
get
{
if (ViewState["detailDirectionState"] == null)
{
ViewState["detailDirectionState"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["detailDirectionState"];
}
set
{
ViewState["detailDirectionState"] = value;
}
}
Here is the click event for one of the flags:
protected void flagAmends_Click(object sender, EventArgs e)
{
LinkButton faBtn = sender as LinkButton;
int lineId = int.Parse(faBtn.CommandArgument);
using (SpamEntities spam = new SpamEntities())
{
SPM_Statement_Lines line = spam.SPM_Statement_Lines.Where(x => x.StatementLineID == lineId).FirstOrDefault();
line.Amended = !line.Amended;
spam.SaveChanges();
}
//reloads gridview
LoadDetails(hidStatus.Value + ";" + hidCategory.Value + ";" + lineId);
}
After the button clicks the button changes colour, and performs the necessary action, however it does not keep its sort - I have been trying to fix this but I have not been successful. I would appreciate any clear step by step solutions.

LinkButtons inside a Grid template to increment and decrement the lables value

protected void Gridproducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hp = new HyperLink();
hp = (HyperLink)e.Row.FindControl("linkSelectprd");
var Pid = DataBinder.Eval(e.Row.DataItem, "product_id").ToString();
var Catid = Request.QueryString["Cid"].ToString();
hp.NavigateUrl = "Sales.aspx?Cid="+Catid+"&"+"Pid="+Pid;
if (!IsPostBack && Request.QueryString["Pid"] != null)
{
this is the variable in which the value of quantity increments
int i=0;
lbltotalquantity.Text = i.ToString() + 1;
}
}
}
}
I use LinkButtons inside a Grid template. I want to be able to raise events when clicking the LinkButtons the value of lable is incremented on + link and decrementd on - link button as lable contains the quantity of Products added to invoice. How can I accomplish this?
I believe this is what you want....
You don't do the increment in RowDataBound because RowDataBound trigger when you are binding the GridView
.aspx
<asp:ScriptManager ID="sm" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="up" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Product">
<ItemTemplate>
<asp:Label ID="lblProduct" runat="server" Text='<%# Eval("Product") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:Label ID="lblQuantity" runat="server" Text="0"></asp:Label>
<asp:LinkButton ID="lbtnPlus" runat="server" Text="+" OnClick="lbtnPlus_Click"></asp:LinkButton>
<asp:LinkButton ID="lbtnMinus" runat="server" Text="-" OnClick="lbtnMinus_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="gv" />
</Triggers>
</asp:UpdatePanel>
.cs
protected void Page_Load(object sender, EventArgs e)
{
// Check
if (!IsPostBack)
{
// Variable
string[] product = { "Dell", "Asus", "Acer", "Toshiba", "Fujishu", "VAIO" };
DataTable dt = new DataTable();
dt.Columns.Add("Product");
for (int i = 0; i < product.Length; i++)
dt.Rows.Add(product[i]);
gv.DataSource = dt;
gv.DataBind();
// Dispose
dt.Dispose();
}
}
private void DoTheMath(GridViewRow row, bool isAdd)
{
// Variable
bool isNumber = false;
int currentValue = 0;
// Find Control
Label lblQuantity = row.FindControl("lblQuantity") as Label;
// Check
if (lblQuantity != null)
{
// Check
if (lblQuantity.Text.Trim() != string.Empty)
{
isNumber = int.TryParse(lblQuantity.Text.Trim(), out currentValue);
// Check
if (isNumber)
{
// Is Add
if (isAdd)
currentValue++;
else
{
// Check cannot be less than 0
if (currentValue > 0)
currentValue--;
}
}
// Set to TextBox
lblQuantity.Text = currentValue.ToString();
}
}
}
protected void lbtnPlus_Click(object sender, EventArgs e)
{
// Get
LinkButton lbtn = sender as LinkButton;
GridViewRow row = lbtn.NamingContainer as GridViewRow;
DoTheMath(row, true);
}
protected void lbtnMinus_Click(object sender, EventArgs e)
{
// Get
LinkButton lbtn = sender as LinkButton;
GridViewRow row = lbtn.NamingContainer as GridViewRow;
DoTheMath(row, false);
}

Cant call Imagebutton in a OnCommand function

I have this in ASP.NET in VS
I have image button in repeater
<asp:Repeater ID="RepeaterImages" runat="server">
<ItemTemplate>
<asp:ImageButton ID="Imagebutton2" runat="server" CssClass="choicebutton" ImageUrl='<%# DataBinder.Eval(Container.DataItem, "answer" )%>' CommandArgument='<%# DataBinder.Eval(Container.DataItem, "question" )%>' CommandName='<%# DataBinder.Eval(Container.DataItem, "answer" )%>' OnCommand="checkAnswer" />
</ItemTemplate>
</asp:Repeater>
and I want to change border color of image button when it is false
public void checkAnswer(object sender, CommandEventArgs e)
{
string trueanswer = e.CommandArgument.ToString();
string urlanswer = e.CommandName.ToString();
if (urlanswer == q_image)
{
}
else
{
// Imagebutoon2 doesnt exist in current context why?
Imagebutton2.BorderColor = Color.Red;
}
}
You can use ItemDataBound for this task:
protected void RepeaterImages_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
RepeaterItem item = e.Item;
if ((item.ItemType == ListItemType.Item) || (item.ItemType == ListItemType.AlternatingItem))
{
Imagebutton Imagebutton2= (Imagebutton)item.FindControl("Imagebutton2");
string trueanswer = Imagebutton.CommandArgument.ToString();
string urlanswer = Imagebutton.CommandName.ToString();
if (urlanswer == q_image)
{
}
else
{
// Imagebutoon2 doesnt exist in current context why?
Imagebutton2.BorderColor = Color.Red;
}
}
}
Do not forget to add this to the repeater server tag: OnItemDataBound="RepeaterImages_ItemDataBound"
UPDATE
If you want this happen when imagebutton is clicked, then it is even more simple. You can use sender to access the imagebutton clicked:
public void checkAnswer(object sender, CommandEventArgs e)
{
ImageButton btn = (ImageButton)sender;
string trueanswer = e.CommandArgument.ToString();
string urlanswer = e.CommandName.ToString();
if (urlanswer == q_image)
{
}
else
{
// Imagebutoon2 doesnt exist in current context why?
btn.BorderColor = Color.Red;
}
}

Find Control In Datalist

When I tried To Find Control n data List As I Mentioned Below
Error(Object reference not set to an instance of an object.
I cannot know
protected void dlCategory_ItemDataBound(object sender, DataListItemEventArgs e)
{
Label Lb = (Label)e.Item.FindControl("LblCat");
Lb.ForeColor = System.Drawing.Color.Red;
}
<Datalist>
<asp:DataList ID="dlSubCategory" runat="server"
DataSource='<%# GetSubCategory(Convert.ToString(Eval("Category_ID")))%>'
onitemcreated="dlSubCategory_ItemCreated"
onitemdatabound="dlSubCategory_ItemDataBound">
<EditItemStyle ForeColor="#CC3300" />
<SelectedItemStyle ForeColor="#CC3300" />
<ItemTemplate>
<div class="buttn_div_sub">
<div class="lm40 tm2 buttn_txt">
<a href='<%# Convert.ToString(Eval("ProductCategory_Id")).Insert(0,"ListView.aspx?ProductCategory_Id=") %>'
class="buttn_txt">
<asp:Label ID="Label1" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"Name") %>'></asp:Label>
</a>
</div>
</div>
</ItemTemplate>
</asp:DataList>
</ItemTemplate>
protected void dlCategory_ItemDataBound(object sender, DataListItemEventArgs e)
{
Label Label1 = e.Item.FindControl("Label1") as Label;
if (LblCat != null)
{
string id = ((System.Data.DataRowView)e.Item.DataItem).Row["ProductCategory_Id"].ToString();
if (Request.QueryString["ProductCategory_Id"] == id)
{
Label1.ForeColor = System.Drawing.Color.Red;
}
}
}
Could you try this? The first item passed to this function will be the header (if present on the datalist) and that's why you get the error.
protected void dlCategory_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Label Lb = (Label)e.Item.FindControl("LblCat"); Lb.ForeColor = System.Drawing.Color.Red;
}
}

Categories

Resources