Gridview check each row and update - c#

I have a gridview ,gridview data is from database.I have a last column which is asp:FileUpload for user to insert new attachment if they want to,thing i wanted to do here is ,my backend c# will check if row asp file upload is not empty,then will upload new revision to that form.if empty,dont upload new revision to that form.
<asp:TemplateField HeaderText="Upload New Form" HeaderStyle-BackColor="DarkBlue" HeaderStyle-Font-Bold="false" HeaderStyle-ForeColor="White" ItemStyle-Width="5%">
<ItemTemplate>
<asp:FileUpload ID="newdoc" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
this is the column i created for user to insert new file if they want.
protected void Button11_Click(object sender, EventArgs e)
{
//System.Diagnostics.Debugger.Launch();
string data = "";
foreach (GridViewRow row in GridView3.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
FileUpload chkRow = (row.Cells[7].FindControl("newdoc") as FileUpload);
if (FileUploadControl.HasFile)
{
string id = row.Cells[2].Text + '-'+row.Cells[3].Text;
data = data + id + ",";
}
}
}
string[] alldata = data.Split(',');
foreach (string dataid in alldata )
{
if (dataid.Equals(""))
continue;
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + dataid + "');", true);
}
}
my c# logic is like this,i will check each row,if the uploadcontrol is not empty then dont add the id into data list,after collect all the row that needed to update new revision i will split the list update it 1 by 1,i try to alert out the id but value i get is empty.any ideas where i did wrong??
i suspeect something wrong in this line " string id = row.Cells[2].Text + '-' + row.Cells[3].Text;"

use BoundField instead of TemplateField..
string test = row.Cells[2].Text;

Related

Trying to use File Upload in Listview? Update not working

Here is my ListView. I'm using the OnItemCommand to reference the code in code-behind. Here I'm trying to Update the database with the new FileUpload control.
<%--Listview--%>
<asp:ListView runat="server" ID="livLocation" class="container"
DataKeyNames="LocationID"
DataSourceID="sdsListViewLocation"
EmptyDataText="No data to display"
InsertItemPosition="FirstItem"
OnItemInserted="livLocation_ItemInserted"
OnItemUpdated="livLocation_ItemUpdated"
OnItemDeleted="livLocation_ItemDeleted"
OnItemCanceling="livLocation_ItemCanceling"
OnItemCommand="livLocation_ItemCommand">
</asp:ListView>
The Insert works perfectly fine. When an Update is executed a Null error is thrown for all FindControls. I believe for some reason the FindControls are not working for the Update. I have tried giving each control their own id's but that still didn't fix the problem. I have been referencing this post but nothing has helped so far: Upload images with fileupload within a Listview asp.net
protected void livLocation_ItemCommand(object sender, ListViewCommandEventArgs e)
{
//
if (e.CommandName == "Insert")
{
// Find controls on insert.
TextBox txtLocation = (TextBox)livLocation.InsertItem.FindControl("txtLocation");
TextBox txtImage = (TextBox)livLocation.InsertItem.FindControl("txtImage");
FileUpload fuiImage = (FileUpload)livLocation.InsertItem.FindControl("fuiImage");
// Get today's date
String strDate = DateTime.Now.ToString("MM-dd-yyyy-h-m-stt");
// If file is there to upload.
if (fuiImage.HasFile)
{
// Set path.
String strFileName = txtLocation.Text + "-" + strDate + ".jpg";
String strPath = Request.PhysicalApplicationPath + "Image\\Location\\" + strFileName;
// Save file.
fuiImage.SaveAs(strPath);
// Fill Image textbox
txtImage.Text = strFileName;
}
else
{
// Do nothing
}
}
else if (e.CommandName == "Update")
{
// Find controls on insert.
TextBox txtLocation = (TextBox)livLocation.InsertItem.FindControl("txtLocation");
TextBox txtImage = (TextBox)livLocation.InsertItem.FindControl("txtImage");
FileUpload fuiImage = (FileUpload)livLocation.InsertItem.FindControl("fuiImage");
// Get today's date
String strDate = DateTime.Now.ToString("MM-dd-yyyy-h-m-stt");
// If file is there to upload.
if (fuiImage.HasFile)
{
// Set path.
String strFileName = txtLocation.Text + "-" + strDate + ".jpg";
String strPath = Request.PhysicalApplicationPath + "Image\\Location\\" + strFileName;
// Save file.
fuiImage.SaveAs(strPath);
// Fill Image textbox
txtImage.Text = strFileName;
}
else
{
// Do nothing
}
}
else if (e.CommandName == "Delete")
{
// Delete file.
FileUpload fuiImage = (FileUpload)livLocation.InsertItem.FindControl("fuiImage");
String strPath = Request.PhysicalApplicationPath + "Image\\Location\\" + fuiImage.FileName;
System.IO.File.Delete("strPath");
}
else
{
// Do nothing
}
}
}
As discussed its always nice to use the sender object for better maintainability later. for your issue kindly visit the following link to get the edited item as your syntax is not correct: https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.listview.itemediting?view=netframework-4.8
it shows more details about item editing and how to fetch the edited item with the new edit index.
the
(TextBox)livLocation.InsertItem is incorrect it must be EditItem
so it will be (FileUpload)(sender as ListView).EditItem.FindControl.....

indiviual files upload asp.net c#

when i click on link button for adding more file upload then this add only 1 .. means 1 file upload which is already visible and 1 which is display on clicking on linkbutton ..
but when i click again on linkbutton for adding more then this not display ..
i try this
ok i do this
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">upload</asp:LinkButton><br />
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
<asp:Button ID="Button1" runat="server" Text="submit" OnClick="Button1_Click" />
</form>
suppose there is file upload control.. when we select file by clicking on browse and then click on upload then file name with extension i.e. abc.doc should be display ... then when we use again same file upload and click on browse and select another file then file will be display i.e. xyz.pdf.. so there is two files abc.doc and xyz.doc .. so this is want to do .. i want to upload files and display these uploaded files
UPDATE
for this i try this
protected void LinkButton1_Click(object sender, EventArgs e)
{
fileuploadd(FileUpload1.FileName);
}
public void fileuploadd(string filename)
{
try
{
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
SMSEntities s = new SMSEntities();
uploaded_file u = new uploaded_file();
{
u.fileupload = filename;
}
s.uploaded_file.Add(u);
s.SaveChanges();
}
//hpf.SaveAs(Server.MapPath("upload") + "\\" + System.IO.Path.GetFileName(hpf.FileName));
Response.Write("<b>File: </b>" + hpf.FileName + " <b>Size:</b> " + hpf.ContentLength + " <b>Type:</b> " + hpf.ContentType + " Uploaded Successfully <br/>");
}
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
}
so when i select file and click on upload then file name is display .. but when i select again file and click on upload then 1st file name is disappear and 2nd file name is display where as i want both ..
so how i display both filenames ... and when click on submit then record files should be inserted in tables individually i am done with this but not with both filename display at a time ..
Create a FileUpload Control on your .aspx like:
<asp:FileUpload runat="server" ID="UploadImages" AllowMultiple="true" />
then in your code behind:
protected void uploadFile_Click(object sender, EventArgs e)
{
if (UploadImages.HasFiles)
{
foreach (HttpPostedFile uploadedFile in UploadImages.PostedFiles)
{
uploadedFile.SaveAs(System.IO.Path.Combine(Server.MapPath("~/Images/"),
uploadedFile.FileName)); listofuploadedfiles.Text += String.Format("{0}<br />", uploadedFile.FileName);
}
}
}
Multiple File Upload
HI Super User Previously I also had same Problem.
What i Actually did was I have Created 5 File Control's For Example
1) FileUpload1
2) FileUpload2
3) FileUpload3
4) FileUpload4
5) FileUpload5
And I have 4 of them as Hidden on load.
On click of 1 st I am showing 2nd One and on click of 2nd I am showing the 3rd one and So on...
In the Controller/Method I am checking if the File Control is not null then proceeding with the normal File Upload Process By taking Array of File Uploads.
<div id="flOther" runat="server">
<div id="fileOtherUploadarea">
<asp:FileUpload ID="flOtherUPL" runat="server" />
</div>
<input style="width: 20px; border: 0px none; background-color:transparent;" id="btnOtherAddMoreFiles" type="button" onclick="AddOtherMoreImages();" class="icon-plus-sign" />|
<asp:LinkButton ID="lnkOtherUpload" OnCommand="btnLnk_UploadOtherFiles" CommandArgument='<%# Eval("ID") %> 'runat="server">Upload Files</asp:LinkButton>
</div>
<script language="javascript" type="text/javascript">
function AddMoreImages() {
if (!document.getElementById && !document.createElement)
return false;
var fileUploadarea = document.getElementById("fileUploadarea");
if (!fileUploadarea)
return false;
var newLine = document.createElement("br");
fileUploadarea.appendChild(newLine);
var newFile = document.createElement("input");
newFile.type = "file";
newFile.setAttribute("class", "fileUpload");
if (!AddMoreImages.lastAssignedId)
AddMoreImages.lastAssignedId = 100;
newFile.setAttribute("id", "FileUpload" + AddMoreImages.lastAssignedId);
newFile.setAttribute("name", "FileUpload" + AddMoreImages.lastAssignedId);
var div = document.createElement("div");
div.appendChild(newFile);
div.setAttribute("id", "div" + AddMoreImages.lastAssignedId);
fileUploadarea.appendChild(div);
AddMoreImages.lastAssignedId++; }
</script>
protected void btnLnk_UploadOtherFiles(object sender, CommandEventArgs e)
{
int ID;
try
{
if (!String.IsNullOrEmpty(Convert.ToString(e.CommandArgument)))
{
ID = Convert.ToInt32(e.CommandArgument);
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
string fileExtension = System.IO.Path.GetExtension(hpf.FileName);
if (ValidExtesion(fileExtension))
{
int MaxSizeAllowed = Convert.ToInt32(ConfigurationManager.AppSettings["MaxFileSize"]);
if (hpf.ContentLength < MaxSizeAllowed)
{
int lastIndex = Convert.ToInt32(hpf.FileName.LastIndexOf("\\"));
string FileName = DateTime.Now.Millisecond + hpf.FileName.Substring(lastIndex + 1);
string FileName1 = hpf.FileName.Substring(lastIndex + 1);
FileName = FileName.Replace(" ", "");
StringBuilder AncTag = new StringBuilder();
AncTag = AncTag.Append("<a href='Attachments/AMT/'" + FileName + "' target='_blank'>'" + FileName1 + "' </a>");
string strAncTag = AncTag.ToString();
strAncTag = strAncTag.Replace("'", "");
hpf.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "Attachments/AMT/" + FileName);
obj.UploadOtherFiles_ProblemDescription(ID, strAncTag);
}
else
{
}
}
else
{
}
}
}
}
}
catch (Exception ex)
{
ErrorLog objER = new ErrorLog(ex);
}
finally
{
obj = null;
grdPDC.EditIndex = -1;
}
}

Download Gridview specific Column data to word file

I have a GridView on a page. The user is able to input data in that GridView then I am downloading an Word file on Submit Event.
Now the question is: How can I download specific Column data to that word file? That word file also contains other data from different fields from same the page, which are working fine.
Below is the code for GridView: (Grid is binding on page load)
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
TextBox box1 = (TextBox)GridViewData11.Rows[rowIndex].Cells[1].FindControl("Data1");
TextBox box2 = (TextBox)GridViewData11.Rows[rowIndex].Cells[2].FindControl("Data2");
TextBox box3 = (TextBox)GridViewData11.Rows[rowIndex].Cells[3].FindControl("Data3");
TextBox box4 = (TextBox)GridViewData11.Rows[rowIndex].Cells[4].FindControl("Data4");
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();
box4.Text = dt.Rows[i]["Column4"].ToString();
rowIndex++;
}
}
Below code is for Download data to Word file:
public void GenerateWordDoc()
{
string strBody = "<html>" +
"<body>" +
"<div> <b> Details </b></div> <br>" +
"<table MAX width=\"701\" height=\"646\" border=\"1\"> <tr><td width=\"191\" height=\"26\" >Name of user </td> <td height=\"86\" > Comments</td><td colspan=\"3\"> </td></tr> </table>" +
"</body>" +
"</html>";
string fileName = “wordfile.doc”;
Response.AppendHeader("Content-Type", "application/msword");
Response.AppendHeader("Content-disposition", "attachment; filename=" + fileName);
Response.Write(strBody);
}

Set Height of a listbx fit to content

I have to set a list box which shows data from database column . Each time different length of data will come to list-box. so according to this I have to change its height fit to content . How is it ?
<asp:ListBox ID="ListBox1" runat="server" BackColor="White" Height="14000px"
Width="1312px"></asp:ListBox>
while (dr.Read())
{
string poem = dr[0].ToString();
byte[] newFileData = Encoding.ASCII.GetBytes(poem);
string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
string[] poem_details = fileString.Split(new string[] { " ", "\n" }, StringSplitOptions.None);
foreach (var line in score_details)
{
ListBox1.Items.Add(line);
}
}
Try this-
Listbox.rows = Listbox.Items.count
OR
you can also set size attribute as follows-
$(document).ready(function() {
$('#<%=this.ListBox1.ClientID%>').attr('size', $('#<%=this.ListBox1.ClientID%> option').length);
});

FileUpload on listview

I have ListView that display info from XML and to save to server from FileUpload that are on this ListView. I dont have problem to write to the XML, the problem is on save the FileUpload to folder.
I belive that i have mistake that i not seperate the listview to itemtemplate and insertemplate and edit...It must to? because the title going to correct place on XML, and even file name. but the file not saved to the folder.
For most tests i did - nothing happent after click on "update" BTN. when i add the int "i" to the items[i] somtimes it just update the xml without saving the file, and sometimes i get error of "out of index".
What is wrong?
ASPX code
<h2><asp:Label ID="LBL_number" runat="server" Text='<%#XPath("id") %>'></asp:Label></h2>
<h2>Small Image</h2> <asp:Image Width="100" CssClass="ltr" runat="server" ID="TB_small" ImageUrl='<%# XPath("small_image_url") %>'></asp:Image><asp:FileUpload ID="FU_small" runat="server" />
<br /><br /><br />
<h2>Big Image</h2> <asp:Image Width="300" CssClass="ltr" runat="server" ID="TB_big" ImageUrl='<%#XPath("big_image_url") %>'></asp:Image><asp:FileUpload ID="FU_big" runat="server" />
<br /><br />
<h2>Title</h2> <asp:TextBox runat="server" ID="TB_title" Text='<%#XPath("title") %>'></asp:TextBox>
<br /><br /><br />
<asp:Button CssClass="btn" ID="Button1" CommandArgument='<%#XPath("id") %>' runat="server" OnClick="update" Text="Update" />
<br />
<asp:Button ID="Button3" CssClass="btn" CommandArgument='<%#XPath("id") %>' runat="server" CommandName="del" OnClick="del" Text="מחק" />
<br /><br />
<br /><br />
</ItemTemplate>
</asp:ListView>
<asp:XmlDataSource ID="XDS_data" runat="server"
DataFile="~/App_Data/AM_data.xml" XPath="/Data/datas/data">
</asp:XmlDataSource>
C# Example only with the small file upload.
protected void update(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load(Path.Combine(Request.PhysicalApplicationPath, "App_Data/AM_data.xml"));
Button myButton = (Button)sender;
int i = Convert.ToInt32(myButton.CommandArgument.ToString());
var FU_small1 = (FileUpload)myButton.FindControl("FU_small");
string extenstion_small = System.IO.Path.GetExtension(FU_small1.FileName);
filename_small = Guid.NewGuid().ToString();
FileUpload fu2 = LV_data.Items[i].FindControl("FU_small") as FileUpload;
if (fu2.HasFile == true)
{
fu2.SaveAs(Server.MapPath("~/imgs/data/big" + filename_small.ToString() + extenstion_small.ToString()));
}
var TB_title = (TextBox)myButton.FindControl("TB_title");
string myString3 = TB_title.Text;
XmlElement el = (XmlElement)doc.SelectSingleNode("Data/datas/data[id='" + i + "']");
el.SelectSingleNode("small_image_url").InnerText = "~/imgs/data" + filename_small + extenstion_small;
el.SelectSingleNode("title").InnerText = myString3;
el.SelectSingleNode("big_image_url").InnerText = "~/imgs/data" + filename_big + extenstion_big;
doc.Save(Path.Combine(Request.PhysicalApplicationPath, "App_Data/AM_data.xml"));
Response.Redirect(Request.RawUrl);
}
There are several problems with your update method:
You need to find control inside container, not inside button. *Wrong approach : * var TB_title = (TextBox)myButton.FindControl("TB_title");
There's no guarantee that id will match ListView's item index. *Wrong approach : * FileUpload fu2 = LV_data.Items[i].FindControl("FU_small") as FileUpload;
etc.
I would suggest to change the method to this:
protected void update(object sender, EventArgs e)
{
int index = 0;
XmlDocument doc = new XmlDocument();
doc.Load(Path.Combine(Request.PhysicalApplicationPath, "App_Data/AM_data.xml"));
Button myButton = (Button)sender;
ListViewItem lvwItem = (ListViewItem)myButton.NamingContainer;
FileUpload FU_small1 = myButton.FindControl("FU_small") as FileUpload;
if (FU_small1 != null && int.TryParse(myButton.CommandArgument, out index))
{
string extenstion_small = System.IO.Path.GetExtension(FU_small1.FileName);
filename_small = Guid.NewGuid().ToString();
TextBox TB_title = myButton.FindControl("TB_title") as TextBox;
string myString3 = TB_title!= null ? TB_title.Text : string.Empty;
if (FU_small1.HasFile == true)
{
FU_small1.SaveAs(Server.MapPath("~/imgs/data/small/" + filename_small + extenstion_small));
}
XmlElement el = (XmlElement)doc.SelectSingleNode("Data/datas/data[id='" + index + "']");
el.SelectSingleNode("small_image_url").InnerText = "~/imgs/data/small/" + filename_small + extenstion_small;
el.SelectSingleNode("title").InnerText = myString3;
el.SelectSingleNode("big_image_url").InnerText = "~/imgs/data/big/" + filename_big + extenstion_big;
doc.Save(Path.Combine(Request.PhysicalApplicationPath, "App_Data/AM_data.xml"));
}
Response.Redirect(Request.RawUrl);
}
And here's a test project I have used to test this.
Finnaly, "foreach" solved it
protected void update(object sender, EventArgs e)
{
//Get xml file
XmlDocument doc = new XmlDocument();
doc.Load(Path.Combine(Request.PhysicalApplicationPath, "App_Data/AM_data.xml"));
//Set button for index it later by CommandArgument
Button myButton = (Button)sender;
foreach (ListViewItem item in LV_data.Items)
{
//Findcontrol of 2 fileupload on listview
FileUpload FU_small1 = (FileUpload)item.FindControl("FU_small1");
FileUpload FU_big1 = (FileUpload)item.FindControl("FU_big1");
//Check if are has file.
if (FU_small1.HasFile && FU_big1.HasFile)
{
//Get extension and genereate random filenames (for avoid ovveride)
FileInfo small_info = new FileInfo(FU_small1.FileName);
FileInfo big_info = new FileInfo(FU_big1.FileName);
string ext_small = small_info.Extension;
string ext_big = big_info.Extension;
string filename_small = Guid.NewGuid().ToString();
string filename_big = Guid.NewGuid().ToString();
//Set i value by button CommandArgument (look on aspx on question)
int i = Convert.ToInt32(myButton.CommandArgument.ToString());
//Get title from TextBox and set string from it
TextBox TB_title = myButton.FindControl("TB_title") as TextBox;
string myString3 = TB_title != null ? TB_title.Text : string.Empty;
//Save the files from the fileuploads we found, and write it on xml
FU_small1.SaveAs(Path.Combine(Request.PhysicalApplicationPath, "imgs/data/thumbs/" + filename_small + ext_small));
FU_big1.SaveAs(Path.Combine(Request.PhysicalApplicationPath, "imgs/data/big/" + filename_big + ext_big));
XmlElement el = (XmlElement)doc.SelectSingleNode("Data/datas/data[id='" + i + "']");
el.SelectSingleNode("small_image_url").InnerText = "~/imgs/data/thumbs/" + filename_small + ext_small;
el.SelectSingleNode("title").InnerText = myString3;
el.SelectSingleNode("big_image_url").InnerText = "~/imgs/data/big/" + filename_big + ext_big;
doc.Save(Path.Combine(Request.PhysicalApplicationPath, "App_Data/AM_data.xml"));
}
}
// Refresh the page
Response.Redirect(Request.RawUrl);
}

Categories