• .NET 读取本地文件绑定到GridViewRow


    wjgl.aspx.cs:

    using System;
    using System.Collections;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Linq;
    using System.IO;
    using DBUtility;
    
    namespace qhsy.DWJSC
    {
        public partial class wjgl : System.Web.UI.Page
        {
    
            protected string File_List = "";
    
            protected void Page_Load(object sender, EventArgs e)
            {
                if (Page.IsPostBack == false)
                {
    
                    if (Request.UrlReferrer.ToString().Contains("wjsc.aspx")==false)
                    {
                        //保存上一页的url传递到wjsc.aspx
                        HttpCookie cookie = new HttpCookie("back");
                        cookie.Values.Add("url", Request.UrlReferrer.ToString());
                        Response.AppendCookie(cookie);        
                    }
                                     
                    lb_title.Text = "文 件 管 理";
    
                    //是否查询
                    string sfcx = Request.QueryString["sfcx"];
                    if (sfcx == "1")
                    {
                        //gridFileList.Columns[0].Visible = false;
                        bg.Visible = false;
    
                    }
    
                    ////是否图片
                    //string sftp = Request.QueryString["sftp"];
                    //if (sftp == "1")
                    //{ 
                    //    //GridView中添加图片缩略图
                    //    gridFileList.Columns[2].Visible = true;
                    //}
    
                    //操作模块id,参数 
                    ViewState["shmkid"] = Request.QueryString["shmkid"];
                    //路径信息    fj = "~/File/JYWJ/8910427356/5209168734/";
                    ViewState["fj"] = Request.QueryString["fj"];
    
    
    
                    string path = string.Format("{0}", (string)ViewState["fj"]);
                    path = Server.MapPath(path);
                    ixExit(path);
    
    
                     //设定初始排序字段为文件修改时间FileLastWriteTime
                     gridFileList.Attributes.Add("SortExpression", "FileLastWriteTime");
                     gridFileList.Attributes.Add("SortDirection", "DESC");
                     BindGrid();
                                
                }
    
    
            }
    
            //绝对路径(目录)是否存在,不存在则创建
            private void ixExit(string path)
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            
            }
    
            //读取本地文件绑定到GridViewRow
            protected void gridFileList_RowDataBound(object sender, GridViewRowEventArgs e)
            {
    
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    Image Img = (Image)e.Row.Cells[0].FindControl("ImgPath");
                    Img.ImageUrl = e.Row.Cells[5].Text;
                    e.Row.Cells[5].Text = "";
    
                }
                DataClass.Comm.gv_hbs(sender, e);
            }
    
    
            //分页
            protected void gridFileList_PageIndexChanging(object sender, GridViewPageEventArgs e)
            {
                gridFileList.PageIndex = e.NewPageIndex;
                this.BindGrid();
            }
    
    
            //绑定gridview
            private void BindGrid()
            {
                //获取数据源
                DataTable dtb = FileDataTable();
    
                //排序
                string SortDirection = gridFileList.Attributes["SortDirection"].ToString();
                string SortExpression = gridFileList.Attributes["SortExpression"].ToString();
                dtb.DefaultView.Sort = string.Format("{0} {1}", SortExpression, SortDirection);
    
                //赋数据源并绑定
                gridFileList.DataSource = dtb;
                gridFileList.DataBind();
                gridFileList.Visible = gridFileList.Rows.Count > 0;
                gridFileList.Attributes.Add("BorderColor", "#000000");
    
            }
    
            private DataTable FileDataTable()
            {
                string fj = (string)ViewState["fj"];
                string path = Server.MapPath(fj);
                GetFiles(path);
    
                //构造DataTABLE
                DataTable dt = new DataTable();
                dt.Columns.Add(new DataColumn("FilePath", typeof(string)));
                dt.Columns.Add(new DataColumn("FileName", typeof(string)));
                dt.Columns.Add(new DataColumn("FileLength", typeof(string)));
                dt.Columns.Add(new DataColumn("FileLastWriteTime", typeof(string)));
                DataRow dr;
    
                //将文件数组集合切割到数组
    
                string[] dtaArry = File_List.Split(',');
    
    
                for (int i = 0; i < dtaArry.Length; i++)
                {
    
                    if (dtaArry[i].Trim() != "")//判断是否为空
                    {
    
                        dr = dt.NewRow();
                        dr[0] = dtaArry[i];//文件路径
                        dr[1] = Path.GetFileName(dtaArry[i]);//文件名
    
                        //获取文件大小(Decimal.Round(Convert.ToDecimal(FI.Length), 2)
    
                        string FIer = dtaArry[i].ToString();
                        FileInfo FI = new FileInfo(FIer);
                        dr[2] = Convert.ToString(Decimal.Round(Convert.ToDecimal(FI.Length / 1024), 2)) + "KB";//获取的是字节byte,还需要转换为千字节KB
    
    
     
                        dr[3] = FI.LastWriteTime;
                        dt.Rows.Add(dr);
    
                    }
    
                }
    
                return dt;
    
            }
    
            
            //遍文件夹下的所有子文件夹下的文件
            public void GetFiles(string ObjDirPath)
            {
                DirectoryInfo SourceDir = new DirectoryInfo(ObjDirPath);
                foreach (FileSystemInfo FSI in SourceDir.GetFileSystemInfos())
                {
    
                    if (FSI is DirectoryInfo)
                    {
    
                        //如果是文件夹则递归
                        GetFiles(FSI.FullName);
                    }
    
                    else
                    {
                        string FilePath = ""; 
                        FilePath = FSI.FullName.ToLower();
    
                        string fj = (string)ViewState["fj"];
                        string mc = fj.Substring(8, 4);
    
                       
                       //FilePath = FilePath.Substring(FilePath.LastIndexOf(mc));                                    
                       File_List += FilePath + ",";
    
                    }
    
                }
    
            }
    
            //排序
            protected void gridFileList_Sorting(object sender, GridViewSortEventArgs e)
            {
    
                string sortExpression = e.SortExpression.ToString();
                string sortdirection = "ASC";
    
                if (sortExpression == gridFileList.Attributes["SortExpression"])
                {
    
                    sortdirection = (gridFileList.Attributes["SortDirection"].ToString() == sortdirection ? "DESC" : "ASC");
    
                }
    
                gridFileList.Attributes["SortExpression"] = sortExpression;
                gridFileList.Attributes["SortDirection"] = sortdirection;
                this.BindGrid();
    
    
            }
    
            protected void btnDel_Click(object sender, EventArgs e)
            {
                try
                {
    
                    FileInfo fileinfo;
                    bool IsSelect = false;
    
                    for (int i = 0; i < gridFileList.Rows.Count; i++)
                    {
    
                        GridViewRow row = gridFileList.Rows[i];
    
                        if (((CheckBox)row.FindControl("chkDel")).Checked)
                        {
    
                            IsSelect = true;
                            Image Img = (Image)gridFileList.Rows[i].Cells[0].FindControl("ImgPath");
                            fileinfo = new FileInfo(Img.ImageUrl);          
                            if (fileinfo.Exists)
                            {
                                fileinfo.Delete();
                                //根据ccid删除表jy_wj_wjccb中的数据
                                string str = string.Format("delete from jy_wj_wjccb where fj='{0}'", Img.ImageUrl.Substring(12, Img.ImageUrl.Length-12));  
                                DbHelperSQL.Query(str);
                            }
                        }
                    }
                    if (IsSelect)
                    {             
                        DataClass.Comm.Alert(Page, "删除成功!");
    
                    }
                    else
                    {
    
                        DataClass.Comm.Alert(Page, "请选择要删除的行!");
    
                    }
                }
                catch (Exception ex)
                {
                    //DataClass.Comm.Alert(Page, ex.ToString());
                }
    
    
    
                BindGrid();
            }
    
            protected void btnAdd_Click(object sender, EventArgs e)
            {
         
                string s = string.Format("~/DWJSC/wjsc.aspx?shmkid={0}&&fj={1}&&sfcg={2}",(string)ViewState["shmkid"], (string)ViewState["fj"], 0);
                Response.Redirect(s);  
                
            }
    
            protected void btBack_Click(object sender, EventArgs e)
            {
            
                Response.Redirect((Request.Cookies["back"].Values["url"]).ToString());
    
                //清空Cookies["back"]
                Response.Cookies["back"].Expires = DateTime.Now.AddDays(-1);  
    
            }
    
        }
    }

     wjgl.aspx:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="wjgl.aspx.cs" Inherits="qhsy.DWJSC.wjgl" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head id="Head1" runat="server">
        <title>文件管理</title>
        <link href="../COMM/CSS/CSS.css" rel="stylesheet" type="text/css" />
        <style type="text/css">
    
    
            #wjgl
        {
            background:#F2FBE5; text-align:center;  vertical-align:middle;
            100%; 
            height: 714px;
        }
            #div
            {
                height: 701px;
            }
        </style>
        <script type="text/javascript">
            function SelAllClick() { 
              var isSelAll = document.getElementById("gridFileList_ctl01_CheckAll").checked;
              for (var i = 2; i < 32; i++) {
                if (i < 10) checkBoxId = "gridFileList_ctl0" + i + "_chkDel";
                else checkBoxId = "gridFileList_ctl" + i + "_chkDel";
                var checkBoxObj = document.getElementById(checkBoxId);
                if (checkBoxObj == undefined || checkBoxObj == null) break;
                checkBoxObj.checked = isSelAll;    
              }
            }
        </script>  
    </head>
    
    <body class="body">
        <form id="form1" runat="server">
        <div id="div" class="div">
        
       
        <div id="wjgl">
        
          <table width="100%">
     
          <tr>
     
            <td>
     
             <div class="divtitle" > 
                    <asp:Panel ID="Panel4"  CssClass="pan"  runat="server" >
                        <asp:Label ID="lb_title" runat="server"  CssClass="lab"   Text=""></asp:Label>
                    </asp:Panel>
                </div>    
     
            </td>
     
          </tr>
     
          <tr>
     
            <td>
     
                 <asp:GridView  runat="server" ID="gridFileList"
                     Width="100%"    HeaderStyle-Height="30"              
     
                     
     
                      OnRowDataBound="gridFileList_RowDataBound" AllowPaging="True"
     
                     PageSize="20" OnPageIndexChanging="gridFileList_PageIndexChanging"
    
                      onsorting="gridFileList_Sorting" BorderStyle="None"    
                     AutoGenerateColumns="false"  >
     
            <Columns>
     
            <asp:TemplateField ItemStyle-CssClass="divcheck"  > 
     
            <ItemStyle HorizontalAlign="Center" />
     
                    <HeaderTemplate>&nbsp;<input id="CheckAll" type="checkbox" onclick="SelAllClick();"  runat="server"/></HeaderTemplate>              
    
                    <ItemTemplate>
     
                        <asp:CheckBox runat="server" ID="chkDel" />
     
                    </ItemTemplate>
     
                </asp:TemplateField>
     
                <asp:TemplateField HeaderText="序号" InsertVisible="False">
     
                  <ItemStyle HorizontalAlign="Center" />
     
                 <ItemTemplate>
     
                     <asp:Label ID="Label2" runat="server" Text='<%# this.gridFileList.PageIndex * this.gridFileList.PageSize + this.gridFileList.Rows.Count + 1%>'/>
     
                </ItemTemplate>
     
                </asp:TemplateField> 
     
                 <asp:TemplateField HeaderText="图片"  Visible="false" InsertVisible="False" >
     
                  <ItemStyle HorizontalAlign="Center" />
     
                 <ItemTemplate>
     
                     <asp:Image ID="ImgPath" runat="server" Width="150" Height="80" />
     
                </ItemTemplate>
     
                </asp:TemplateField> 
     
               <asp:BoundField DataField="FileName" HeaderText="名称" SortExpression="FileName" >
     
                    <ItemStyle HorizontalAlign="Center" />
     
                </asp:BoundField> 
     
                <asp:BoundField DataField="FileLength"  HeaderText="大小" SortExpression="FileLength" >
     
                    <ItemStyle HorizontalAlign="Center" />
     
                </asp:BoundField> 
                
                   <asp:BoundField DataField="FilePath"    SortExpression="FilePath">
     
                    <ItemStyle HorizontalAlign="Center" />
     
                </asp:BoundField>
     
                <asp:BoundField DataField="FileLastWriteTime" HeaderText="修改时间" SortExpression="FileLastWriteTime" >
     
                    <ItemStyle HorizontalAlign="Center" />
     
                </asp:BoundField> 
     
            </Columns>
     
        </asp:GridView>
        
       
            </td>
     
          </tr>
     
           <tr id="bg" runat="server">
                <td align="center" class="sub_bg">      
                    <asp:Button runat="server" ID="btnAdd" Text="添加文件" OnClick="btnAdd_Click" style="height: 26px" />&nbsp;
                <asp:Button runat="server" ID="btnDel" Text="删除文件" OnClick="btnDel_Click" OnClientClick="return confirm('提示:确定要删除吗?');" />
                &nbsp;
                 
    
                    <asp:Button ID="btBack" runat="server" Text="返回上一页" onclick="btBack_Click" />
                 
    
                    </td>
            </tr>
         </table>
    
    
        </div>
         </div>
        </form>
    </body>
    </html>
  • 相关阅读:
    开源高性能网络库Libevent的简介
    网络IO之阻塞、非阻塞、同步、异步总结【转】
    C语言20150620
    EF那点事
    SSO单点登录的实现原理是怎样的
    SQL索引器
    基础数学知识
    hibernate优化笔记(随时更新)
    JAVA中保留小数的多种方法
    Hibernate的session缓存和对象的四种状态
  • 原文地址:https://www.cnblogs.com/yangwujun/p/5151107.html
Copyright © 2020-2023  润新知