file upload in gridview - c#

I need to add a column with a file upload control to my grid view so that I can upload files against any particular row. Is it possible to do this, ideally I need to be able to do this without putting the gridview into it's edit state.

You can use this within the as follows:
<asp:TemplateField HeaderText="UploadImage">
<ItemTemplate>
<asp:Image ImageUrl="~/images/1.jpg" runat="server" ID="image" /> // shown only when not in edit mode
</ItemTemplate>
<EditItemTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" /> // shown only in edit mode
</EditItemTemplate>
</asp:TemplateField>
At last include a as follows to enter edit mode.
<asp:commandField showEditButton="true" showCancelButton="true">
Then add two events as follows:
protected void GridView1_RowEditing(object sender, GridViewUpdateEventArgs e)
{
gvwID.EditIndex=e.NewEditIndex;
BindGrid();
}
protected void GridView1_RowCancelEdit(object sender, GridViewUpdateEventArgs e)
{
gvwID.EditIndex=-1;
BindGrid();
}
The FileUpload control, will not automatically save the uploaded file. To save the file you need to use the FileUpload control’s SaveAs method. Before you can use the SaveAs method you need to get the instance of the FileUpload control for the row you are editing. To get the instance of the control you can hook up to the GridView’s RowUpdating event. The following code will get the instance of the FileUpload control and save the uploaded file:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int RowID=Convert.ToInt32(gvwID.DataKeys[e.RowIndex].value);
FileUpload fileUpload = GridView1.Rows[e.RowIndex].FindControl("FileUpload1") as FileUpload;
if(fileUpload.HasFile)
{
fileUpload.SaveAs(System.IO.Path.Combine(Server.MapPath("Images"), fileUpload.FileName));
//update db using the name of the file corresponding to RowID
}
gvwID.EditIndex=-1;
BindGrid();
}
Hope this will help...

The following link will help you:
http://msdn.microsoft.com/en-us/library/7tas5c80.aspx
It has a sample code for adding a DateTimePicker to datagridview cell.
You may add the fileupload control the same way...
Hope this helps...

Sudha have a great post with full functionality of file upload in GridView:
Fileupload control in gridview?
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID"
DataSourceID="AccessDataSource1" Width="148px" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblFileUpLoad" runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="true" ShowDeleteButton="true" />
</Columns>
</asp:GridView>
....

The EditTemplate looks like this:
<EditItemTemplate>
<asp:TextBox ID="txtImage" runat="server" Text='<%# Bind("Image") %>' Visible="False"></asp:TextBox>
<asp:FileUpload ID="FileUpload1" runat="server" />
</EditItemTemplate>
In code behind this will upload the file on Row Update:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex] as GridViewRow;
FileUpload FileUpload1 = (FileUpload)GridView1.Rows[e.RowIndex].FindControl("FileUpload1");
if (FileUpload1 != null && FileUpload1.HasFile)
{
FileUpload1.SaveAs(Server.MapPath("~/uploads/" + myfilename));
}
}
This check is in place in case no file is selected so previous name is picked. Note in edit template we have placed a textbox that has visibility set to false which binds to the image name in the DB
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (GridView1.EditIndex == -1) return;
FileUpload fileUpLoad = GridView1.Rows[GridView1.EditIndex].FindControl("FileUpload1") as FileUpload;
string fileName = fileUpLoad.FileName;
TextBox txtImage = GridView1.Rows[GridView1.EditIndex].FindControl("txtImage") as TextBox;
if (fileUpLoad != null && fileUpLoad.HasFile)
{
txtImage.Text = fileUpLoad.FileName;
}
else
{
txtImage.Text = txtImage.Text;
}
}

<asp:ScriptManager runat="server" ID="scm"></asp:ScriptManager>
<asp:UpdatePanel runat="server" ID="upMain" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView AutoGenerateColumns="False" runat="server" ID="dt">
<Columns>
<asp:TemplateField HeaderText="Catagory">
<ItemTemplate>
<asp:DropDownList runat="server" ID="ddlSubCat">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Attachments">
<ItemTemplate>
<asp:UpdatePanel runat="server" UpdateMode="Conditional" ID="updFU"> <ContentTemplate>
<asp:FileUpload runat="server" ID="updCon" /><asp:Button runat="server" ID="btnUpload" Text="Upload" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnUpload" />
</Triggers>
</asp:UpdatePanel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>

Related

how can i delete a gridview row? while the data is not yet saved in the database

i have a system that adds items into the DataGrid, my question is how can i use the delete button? when the user wants the item deleted, user will press the button to delete the row, but i cant seem to make it work. thank you!
<asp:GridView runat="server" ID="gridview" CssClass="table-hover" AutoGenerateColumns="true" HeaderStyle-BackColor="CornflowerBlue" BackColor="White" BorderWidth="5" BorderColor="CornflowerBlue" OnSelectedIndexChanged="gridview_SelectedIndexChanged" CellPadding="8"
CellSpacing="0" Width="100%" OnRowDeleting="gridview_RowDeleting" EmptyDataText="No records to display">
<HeaderStyle BackColor="CornflowerBlue"></HeaderStyle>
<Columns>
<asp:CommandField ShowDeleteButton="true" ButtonType="Button" />
<asp:TemplateField ItemStyle-Width="25px" HeaderText="">
<ItemTemplate>
<asp:ImageButton ID="lnkEdit" runat="server" ImageUrl="~/Images/Icons/Modify.png" OnClick="Edit" />
<%--<asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" OnClick="Edit"></asp:LinkButton>--%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
here is my script
<script runat="server">
void gridview_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
TableCell cell = gridview.Rows[e.RowIndex].Cells[2];
}
</script>
grid view picture
In Gridview add OnRowCommand="gridview_RowCommand"
CommandField can work but I go like this:
<asp:TemplateField ItemStyle-Width="25px" HeaderText="">
<ItemTemplate>
<asp:Button ID="lnkDel" runat="server" Text="Delete" CommandName="Del" CommandArgument='<%#Eval("ID")%>' />
</ItemTemplate>
</asp:TemplateField>
In code behind
protected void gridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Del") {
//Get Command Argument
int IdToDelete = Convert.ToInt32( e.CommandArgument.ToString());
//Your Delete Command
//Rebind GridView
}
}

Get textbox.text from nested gridview

I have a parent gridview with a child gridview
<!-- Parent -->
<asp:GridView ID="gvParent" runat="server" AutoGenerateColumns="false" Width="100%" CssClass="Grid"
DataKeyNames="SupplierReference" OnRowDataBound="gvParent_OnRowDataBound" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt = "" style="cursor: pointer" src="images/plus.png" />
<asp:Panel ID="pnlOrders" runat="server" Style="display: none">
<!-- Child -->
<asp:GridView ID="gvChild" runat="server" AutoGenerateColumns="false" CssClass = "ChildGrid"
ShowFooter = "true" OnRowDataBound="gvChild_OnRowDataBound">
<Columns>
<asp:TemplateField HeaderText="Qty" ItemStyle-Width="100px">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%#Eval("Qty")%>' />
</ItemTemplate>
</asp:TemplateField >
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkSelectQtys" runat="server"
CommandArgument = '<%# Eval("SupplierReference")%>' CommandName="SelectQtys"
OnClientClick = "return confirm('Add these materials to this task?')"
Text = "Add" OnClick="getQty" ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I am trying to have a textbox that the user can alter the value and when they click add I want to be able to pull that text into the C# code and work with it.
I cant get it into my C# code.
protected void getQty(object sender, EventArgs e)
{
//After clicking "add"....
//Do something here to get text from each TextBox1 in the Child gridview
}
Someone please help before I lose what little hair I have left...
protected void getQty(object sender, EventArgs e)
{
//After clicking "add"....
string s;
for(i=0; i < gvChild.Rows.Count; i++)
{
s = ((TextBox)gvChild.Rows[i].FindControl("TextBox1")).Text;
}
//Do what you want to with this string
}

how to get the specific row value from corresponding button click in gridview [duplicate]

This question already has answers here:
ASP GridView get row values on button click
(2 answers)
Closed 7 years ago.
I have declared a gridview where some fields are bound from database. I have added a item template where I have got a textbox and button. Now when I click the button, I want to catch the values of a column and that textbox of that corresponding row. How can I get it done?
My aspx gridview markup:
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="FOODITEM_ID" DataSourceID="SqlDataSource2" EnableModelValidation="True" OnSelectedIndexChanged="GridView2_SelectedIndexChanged"
OnRowCommand="GridView2_OnRowCommand">
<Columns>
<asp:BoundField DataField="FOOD_ITEM_NAME" HeaderText="FOOD_ITEM_NAME" SortExpression="FOOD_ITEM_NAME" />
<asp:BoundField DataField="FOODITEM_ID" HeaderText="FOODITEM_ID" ReadOnly="True" SortExpression="FOODITEM_ID" />
<asp:BoundField DataField="PRICE" HeaderText="PRICE" SortExpression="PRICE" />
<asp:BoundField DataField="DAY_AVAILABLE" HeaderText="DAY_AVAILABLE" SortExpression="DAY_AVAILABLE" />
<asp:BoundField DataField="TIME_AVAILABLE" HeaderText="TIME_AVAILABLE" SortExpression="TIME_AVAILABLE" />
<asp:BoundField DataField="DISCOUNT_PERCENTAGE" HeaderText="DISCOUNT_PERCENTAGE" SortExpression="DISCOUNT_PERCENTAGE" />
<asp:BoundField DataField="START_DATE" HeaderText="START_DATE" SortExpression="START_DATE" />
<asp:BoundField DataField="DEADLINE" HeaderText="DEADLINE" SortExpression="DEADLINE" />
<asp:BoundField DataField="Rating" HeaderText="Rating" SortExpression="Rating" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="Add"
Text="Add" CommandArgument='<%# ((GridViewRow) Container).RowIndex %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Now when I press the the button, how can i get the textbox and other fields' values of that corresponding row.
There are coupe of things you are missing, so I have decided to give you mine complete sample.
First aspx code. Take notice I use CommandNames (Edit, Delete, Cancel, Update) for appropriate command.
Second, I have binded "ItemsGridView_RowUpdating" to catch new values (this is what are you looking for).
<asp:GridView ID="ItemsGridView" runat="server" DataKeyNames="ItemId,FieldName" PageSize="1000"
AutoGenerateColumns="False" AllowPaging="False" AllowSorting="False" SkinID="DefaultGridView"
OnRowEditing="ItemsGridView_RowEditing"
OnRowCancelingEdit="ItemsGridView_RowCancelingEdit"
OnRowDeleting="ItemsGridView_RowDeleting"
OnRowUpdating="ItemsGridView_RowUpdating"
>
<Columns>
<asp:TemplateField ItemStyle-CssClass="TemplateFieldFourColumns">
<ItemTemplate>
<asp:ImageButton ID="ibEdit" runat="server" ToolTip="<% $resources:AppResource,Edit %>" SkinID="EditPage" CommandName="Edit" />
<asp:ImageButton ID="ibDelete" runat="server" ToolTip="<% $resources:AppResource,Delete %>" SkinID="DeletePage" CommandName="Delete" OnClientClick='<%#this.GetDeleteConfirmation() %>' />
<asp:ImageButton ID="ibUp" runat="server" ToolTip="<% $resources:AppResource,Up %>" SkinID="UpPage" OnClick="ibUp_Click" CommandArgument='<%#Eval("ItemId")%>' />
<asp:ImageButton ID="ibDown" runat="server" ToolTip="<% $resources:AppResource,Down %>" SkinID="DownPage" OnClick="ibDown_Click" CommandArgument='<%#Eval("ItemId")%>' />
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ID="ibCancel" runat="server" ToolTip="<% $resources:AppResource,Cancel %>" SkinID="Cancel" CommandName="Cancel" />
<asp:ImageButton ID="ibUpdate" runat="server" ToolTip="<% $resources:AppResource,Save %>" SkinID="Save" CommandName="Update" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="<% $resources:AppResource,Format %>">
<ItemTemplate>
<asp:Label ID="lblFormat" runat="server" Text='<%#Eval("Format")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFormat" runat="server" Text='<%#Bind("Format")%>' Width="50"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Nov code behind:
protected void ItemsGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
ItemsGridView.EditIndex = e.NewEditIndex;
ItemsGridView.DataSource = this.genericForm.FormItems; //TODO: get your data source
ItemsGridView.DataBind();
}
protected void ItemsGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
ItemsGridView.EditIndex = -1;
ItemsGridView.DataSource = this.genericForm.FormItems; //TODO: get your data source
ItemsGridView.DataBind();
}
protected void ItemsGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//delete...
try
{
Guid itemId = (Guid)e.Keys[0]; //key
//TODO: delete your item and bind new data
}
catch (Exception ex)
{
this.MessageBoxError(ex);
}
}
protected void ItemsGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//update...
try
{
//get your key and read new values for update....
Guid itemId = (Guid)e.Keys[0];
string fieldName = (string)e.Keys[1];
string Format = (string)e.NewValues["Format"];
//TODO: make an update and rebind your data
}
catch (Exception ex)
{
this.MessageBoxError(ex);
}
}
Happy coding!
Flowwing code should work:
void GridView2_OnRowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Add")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = CustomersGridView.Rows[index];
string otherFieldText = row.Cells[0].Text; // put othe fields' index
TextBox txt = (TextBox)row.FindControl("TextBox1"); // Textbox
string txtVal = txt.text; // Textbox value
}
}

Hide Column In Grid

This is my html mark-up and adding the visibility to false in the div tag hides the actual data itself, but just leaves a blank column. I tried to access the div tag (yes I added the runat="server" tag to the html) and attempted to access it like so hideme.Visible = true; which threw a compile error of
Does not exist in the current context.
What should I alter/modify to ensure that this column is completely hidden from my grid?
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" ShowFooter="true"
onrowdatabound="GridView1_RowDataBound" onrowcreated="GridView1_RowCreated">
<Columns>
<asp:BoundField DataField="abcd" HeaderText="abcd" />
<asp:BoundField DataField="def" HeaderText="def" />
<asp:BoundField DataField="hij" HeaderText="hij" />
<asp:BoundField DataField="xyz" HeaderText="xyz" />
<asp:BoundField DataField="eee" HeaderText="eee" />
<asp:BoundField DataField="era" HeaderText="era" />
<asp:BoundField DataField="nai" HeaderText="nai" />
<asp:BoundField DataField="fac" HeaderText="fac" />
<asp:TemplateField>
<ItemTemplate>
<div runat="server" style="visibility:hidden" id="hideme">
<asp:Label ID="lbllunch" runat="server" Text='<%# Eval("hij") %>' />
<asp:Label ID="lbllunchoverage" runat="server" Text='<%# Eval("xyz") %>' />
<asp:Label ID="lbleee" runat="server" Text='<%# Eval("eee") %>' />
<asp:Label ID="lblera" runat="server" Text='<%# Eval("era") %>' />
<asp:Label ID="lblnai" runat="server" Text='<%# Eval("nai") %>' />
<asp:Label ID="lblfac" runat="server" Text='<%# Eval("fac") %>' />
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
EDIT
I added the .Visible command to my page load event (where I always hide anything on my page) like so:
protected void Page_Load(object sender, EventArgs e)
{
hideme.Visible = false;
/More here
}
Since hideme is inside the GridView TemplateField, you can't access it in Page_Load method, however you can access it in GridView1_RowDataBound method as below
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// find the hideme div
HtmlGenericControl div = (HtmlGenericControl)e.Row.FindControl("hideme");
// set the visible property
div.Visible = false;
}
}
You can hide the column in DataBound event of gridview.
protected void GridView_DataBound(object sender, GridViewRowEventArgs e)
{
GridView.Columns[8].Visible = false;
}
If you want to hide template field column why you are adding it to markup. Yes if you keep style="visibility:hidden" it will show blank column only because item template still exists as column.
My suggestion for you is if dont need column dnt add markup.

Create hyperlink button cells in gridview using C# asp.net

I am having a GridView in my web page. Which is displaying the data with the columns as Status, Name , Id and Action. My status column always filled with the 3 values(Complete, Queued and Failed) randomly.
Now I want to display this status column values as a link ,If it is having the value either "Failed" or "Queued". But "Complete" status should not be display as a link.
How Can I achive this design during the runtime?
My Code for binding the data into the grid is,
protected void Page_Load(object sender, EventArgs e)
{
DataTable dtActionList = clsactionList.GetADActionList();
grdADActionList.DataSource = dtActionList;
grdADActionList.DataBind();
}
protected void grdADActionList_RowDataBound(object sender, GridViewRowEventArgs e)
{
foreach (GridViewRow gvr in grdADActionList.Rows)
{
if ((gvr.FindControl("Label1") as Label).Text == "Completed")
{
(gvr.FindControl("Label1") as Label).Visible = true;
(gvr.FindControl("HyperLink1") as HyperLink).Visible = false;
}
}
}
using this code I am just simply binding the values in the grid. I am not able to create the Status column as having link buttons based on the binded values for that status column.
My .aspx Code is:
<asp:GridView ID="grdADActionList" runat="server" Height="83px" Width="935px" AutoGenerateColumns="false" OnRowDataBound="grdADActionList_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Status" SortExpression="Status">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='http://localhost:52807/Default.aspx?'><%# Eval("Status") %>
</asp:HyperLink>
<asp:Label ID="Label1" runat="server" Text="<%# Container.DataItem %>" Visible="False"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="GivenName" HeaderText="GivenName"/>
Please help me to do this further....
On GridViewDataBound event, just hide the link and display a simple label if the value is complete.
ASP.NET:
<asp:TemplateField HeaderText="Status" SortExpression="Status">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='your_url'>
<%# Eval("Status") %>
</asp:HyperLink>
<asp:Label ID="Label1" runat="server" Text="<%# Eval("Status") %>" Visible="False"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
C#:
protected void onGridViewDataBound()
{
foreach(GridViewRow gvr in grd)
if((gvr.FindControl("Label1") as Label).Text.ToLower() == "complete") // Updated Line
{
(gvr.FindControl("Label1") as Label).Visible = true;
(gvr.FindControl("HyperLink1") as HyperLink).Visible = false;
}
}
you have to work in design file means .aspx file
you have to use and
<asp:GridView ID="GridView1" runat="server" EnableModelValidation="True">
<asp:TemplateField HeaderText="Hyperlink">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl='<%# Eval("CODE", #"http://localhost/Test.aspx?code={0}") %>'
Text='link to code'>
</asp:HyperLink>
</ItemTemplate>
You can place an handler on RowDataBound event
protected void gw_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView v_DataRowView = (DataRowView)e.Row.DataItem;
string NavigateUrl = <....place your link here with DataRowView info>
e.Row.Attributes.Add("onclick", NavigateUrl);
}
}
For now you have your columns auto generated, so first disable that feature. Then you need to define each column as a BoundField, and for the hypelink, taking into account your condition, the best way is to define template field:
<asp:GridView ID="grdADActionList" runat="server" BorderStyle="Double" BorderWidth="3px"
Height="83px" Width="935px"
AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name"/>
<asp:BoundField DataField="Action" HeaderText="Action"/>
<asp:BoundField DataField="Id" HeaderText="Id"/>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:HyperLink runat="server" NavigateUrl="~/link/address" Text='<%# Eval("Status") %>'
Visible='<%# (int)Eval("Status") != 1 %>'/>
<asp:Label runat="server" Text='<%# Eval("Status") %>'
Visible='<%# (int)Eval("Status") == 1 %>'>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Note that this is just a variation - you have not specified what values does Status column contain, so I assumed this is int-based enumeration.

Categories

Resources