none
为什么Datalist不能显示图片,和删除数据呢?下星期3就要交了,麻烦帮帮忙 RRS feed

  • 问题

  • 能上传图片到文件夹里,但datalist不能显示图片,而且不能实现删除功能,麻烦各位帮帮忙,谢谢

    public partial class Default2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                DBBind();
            Image1.AlternateText = "图片尚未上传";
            Label1.Visible = false;
            Label2.Visible = false;

        }
        public void DBBind()
        {
            int curpage=Convert.ToInt32(this.Label5.Text);
            PagedDataSource ps=new PagedDataSource();
            OleDbConnection conn = new OleDbConnection();
            conn.ConnectionString = "Provider=Microsoft.Jet.OleDb.4.0;" + "Data Source=" + Server.MapPath("App_Data/eshop.mdb.mdb");
            conn.Open();
            string strSQL = "select * from 图片";
            OleDbDataAdapter da = new OleDbDataAdapter(strSQL, conn);
            DataSet ds = new DataSet();
            da.Fill(ds, "goods");
            ps.DataSource = ds.Tables["goods"].DefaultView;
            ps.AllowPaging = true;
            ps.PageSize = 2;
            ps.CurrentPageIndex = curpage - 1;
            this.LinkButton2.Enabled = true;
            this.LinkButton3.Enabled = true;
            this.LinkButton4.Enabled = true;
            this.LinkButton5.Enabled = true;
            if (curpage == 1)
            {
                this.LinkButton2.Enabled = false;
                this.LinkButton3.Enabled = false;
            }
            if (curpage == ps.PageCount)
            {
                this.LinkButton4.Enabled = false;
                this.LinkButton5.Enabled = false;
            }
            this.Label7.Text = Convert.ToString(ps.PageCount);
            DataList1.DataSource = ps;
            //DataList1.DataKeyField = "goodsid";
            DataList1.DataBind();
            conn.Close();
        }
       
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                string name = FileUpload1.PostedFile.FileName;
                FileInfo file = new FileInfo(name);
                string filename = file.Name;
                string webfilepath = Server.MapPath("images/" + filename);
                string filecontenttype = FileUpload1.PostedFile.ContentType;
                if (filecontenttype == "image/bmp" || filecontenttype == "image/gift" || filecontenttype == "image/pjpeg")
                {
                    if (!File.Exists(webfilepath))
                    {
                        try
                        {
                            FileUpload1.SaveAs(webfilepath);
                            Label1.Visible = true;
                            Label2.Visible = true;
                            Label1.Text = "文件" + filename + "成功上传," + "文件大小为:" + FileUpload1.PostedFile.ContentLength + "字节";
                            Image1.Visible = true;
                            Image1.ImageUrl = "images/" + filename;
                            Image1.Width = 200;
                            Image1.Height = 150;
                            Label2.Text = "按200*150大小显示";
                        }
                        catch (Exception ex)
                        {
                            Label1.Visible = true;
                            Label1.Text = "文件上传失败,失败原因:" + ex.Message;
                        }
                    }
                    else
                    {
                        Label1.Visible = true;
                        Label1.Text = "文件已经存在,请重命名后上传";
                    }
                }
                else
                {
                    Label1.Visible = true;
                    Label1.Text = "文件类型不符,只能上传*.bmp,*.jpg,*.gif类型的文件";
                }
            }
            else
            {
                Label1.Visible = true;
                Label1.Text = "请选择文件或输入文件路径及名称!";
            }
        }
        protected void Button2_Click(object sender, EventArgs e)
        {
            OleDbConnection conn = new OleDbConnection();
            conn.ConnectionString = "Provider=Microsoft.Jet.OleDb.4.0;" + "Data Source=" + Server.MapPath("App_Data/eshop.mdb.mdb");
            conn.Open();
            string fileExt = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName).ToLower();
            string newfile = DateTime.Now.ToString("yyMMddhhmmss") + fileExt;
            string webfilepath = Server.MapPath(@"~\Images\" + newfile);
            string strSQL = "insert into 图片(MapNameUrl,MapName,Map_SysData) values('" + webfilepath + "','" + newfile + "','" + DateTime.Now + "')";
            OleDbCommand com = new OleDbCommand(strSQL, conn);
            com.ExecuteNonQuery();
            FileUpload1.SaveAs(webfilepath);
            conn.Close();

        }
        protected void LinkButton2_Click(object sender, EventArgs e)
        {
            this.Label5.Text = "1";
            this.DBBind();
        }

        protected void LinkButton3_Click(object sender, EventArgs e)
        {
            this.Label5.Text = Convert.ToString(Convert.ToInt32(this.Label5.Text) - 1);
            this.DBBind();
        }
        protected void LinkButton4_Click(object sender, EventArgs e)
        {
            this.Label5.Text = Convert.ToString(Convert.ToInt32(this.Label5.Text) + 1);
            this.DBBind();
        }

        protected void LinkButton5_Click(object sender, EventArgs e)
        {
            this.Label5.Text = this.Label7.Text;
            this.DBBind();
        }
        protected void LinkButton1_Click(object sender, EventArgs e)
        {
          
        }
        protected void DataList1_DeleteCommand(object source, DataListCommandEventArgs e)
        {
            OleDbConnection conn = new OleDbConnection();
            conn.ConnectionString = "Provider=Microsoft.Jet.OleDb.4.0;" + "Data Source=" + Server.MapPath("App_Data/eshop.mdb.mdb");
            conn.Open();
            string M_ID = DataList1.DataKeys[e.Item.ItemIndex].ToString();
            string strDel = "delete from 图片 where Map_ID='" + M_ID + "'";
            OleDbCommand delCom = new OleDbCommand(strDel, conn);
            delCom.ExecuteNonQuery();
            conn.Close();
            DataList1.EditItemIndex = -1;
            OleDbConnection con = new OleDbConnection();
            conn.ConnectionString = "Provider=Microsoft.Jet.OleDb.4.0;" + "Data Source=" + Server.MapPath("App_Data/eshop.mdb.mdb");
            conn.Open();
            OleDbDataAdapter dr = new OleDbDataAdapter("select*from 图片", con);
            DataSet ds = new DataSet();
            dr.Fill(ds, "UserTab");
            DataList1.DataKeyField = "Map_ID";
            DataList1.DataSource = ds;
            DataList1.DataBind();
           
        }
    }
    2009年12月25日 8:59

答案

  • 此代码只是为了演示,上传和添加数据我都写在按钮里了并做了简化,数据库表我只用了2个字段一个id,一个图片名称,图片不显示是你路径不对,删除不好使请给你的删除按钮CommandName="delete"属性,代码如下

     //增加
        protected void Button2_Click(object sender, EventArgs e)
        {
            OleDbConnection conn = new OleDbConnection(ConfigurationManager.AppSettings["connection"]);
            conn.Open();
            bool Flage=false;
            //取的上传文件扩展名
            string fileExt = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName).ToLower();
            //定义一个数字允许上传图片的扩展名
            string[] AgreeExPentFile = new string[] { ".jpg", ".jpeg", ".gif", ".bmp"};
            if (FileUpload1.HasFile)
            {
                for (int i = 0; i < AgreeExPentFile.Length; i++)
                {
                    if (fileExt.Equals(AgreeExPentFile[i]))
                    {
                       Flage = true;
                    }
                }
                if (Flage)
                {
                    //重新定义上传文件名称 例如:091221013516.jpg
                    string newfile = DateTime.Now.ToString("yyMMddhhmmss") + fileExt;
                    //讲图片上传到文件夹upload目录下
                    string webfilepath = Server.MapPath("upload/" + newfile);
                    string strSQL = "Insert Into BL_Table(b_img,b_date) Values('" + newfile + "','" + DateTime.Now + "')";
                    OleDbCommand com = new OleDbCommand(strSQL, conn);
                    com.ExecuteNonQuery();
                    FileUpload1.SaveAs(webfilepath);
                    conn.Close();
                    DBBind();//调用你的刷新方法
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), "jsalert", "alert('图片格式不正确')", true);
                    return;
                }
            }       
        }
        //删除
        protected void DataList1_DeleteCommand(object source, DataListCommandEventArgs e)
        {
            OleDbConnection conn = new OleDbConnection(ConfigurationManager.AppSettings["connection"].ToString());
            conn.Open();
            Int32 Id =Convert.ToInt32(DataList1.DataKeys[e.Item.ItemIndex]);
            string strDel = "Delete From BL_Table Where Id=" + Id;
            OleDbCommand com = new OleDbCommand(strDel, conn);
            com.ExecuteNonQuery();
            conn.Close();
            DBBind();//调用你的刷新方法
        }
    <asp:DataList ID="DataList1" runat="server" DataKeyField="id" Height="168px" OnDeleteCommand="DataList1_DeleteCommand"
            RepeatColumns="4" RepeatDirection="Horizontal" Width="687px">
            <ItemTemplate>
                <asp:Image ID="Image2" ImageUrl='<%# "upload/"+Eval("b_img") %>' runat="server" Height="100px" Width="100px" />
               <!--或者采用html标签 <img src="upload/<%# Eval("b_img") %>" alt="ToolTip" width="100px" height="100px" /> -->
                <br />
                <asp:LinkButton ID="LinkButton1" runat="server" CommandName="delete">删除</asp:LinkButton>
            </ItemTemplate>
        </asp:DataList>
    2009年12月25日 12:45
  • 你好,

    希望你已经解决了你的问题。
    如果显示图片的问题仍然没有解决,请注意你说的数据库中的图片路径为D:\12.19\images\091225125129。

    如果你直接把这个绑定到Image控件上当然不行了。你可以获得图片的名字,然后把它转换成web地址,如~/images/091225125129.jpg。
    Microsoft Online Community Support
    2009年12月28日 3:42
  • 你好!

    针对你的情况我写了个完事的示例,你参照这个例子,修改一下你的代码。

    <%@ Page Language="C#" AutoEventWireup="true" %>
    <%@ Import Namespace="System.IO" %>
    <%@ Import Namespace="System.Data" %>
    <%@ Import Namespace="System.Data.OleDb" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <script runat="server">
    
        const string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\DB.mdb;";
        private string fImageDirectory;
        public string ImageDirectory
        {
            get
            {
                if (String.IsNullOrEmpty(fImageDirectory))
                    fImageDirectory = Server.MapPath("Images");
    
                return fImageDirectory;
            }
        }
        private string fImageDirectoryUrl;
        private string ImageDirectoryUrl
        {
            get
            {
                if (String.IsNullOrEmpty(fImageDirectoryUrl))
                    fImageDirectoryUrl = String.Format("http://{0}/Images/", Request.Url.Authority);
                
                return fImageDirectoryUrl;
            }
        }
    
        protected void Page_Load(object sender, EventArgs e)
        {
            /* 表结构
             * 表名: Images
             * ID 文本
             * ImageName 文本
             * ImagePhysicalName 文本
             */
            if (!this.IsPostBack)
                this.BindList();
        }
        
        private void BindList()
        {
            string commandText = "SELECT * FROM [Images]";
    
            using (OleDbDataAdapter da = new OleDbDataAdapter(commandText, connectionString))
            {
                DataSet ds = new DataSet();
                da.Fill(ds);
                
                this.DataList1.DataSource = ds.Tables[0];
                this.DataList1.DataBind();
            }
        }
        
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (this.FileUpload1.HasFile)
            {
                string id = Guid.NewGuid().ToString();
                string imageName = Path.GetFileName(this.FileUpload1.PostedFile.FileName);
                string imagePhysicalName = String.Format("{0}{1}", id, Path.GetExtension(imageName));
                string imagePath = Path.Combine(this.ImageDirectory, imagePhysicalName);
    
                // 保存物理文件
                this.FileUpload1.SaveAs(imagePath);
    
                // 添加数据
                using (OleDbConnection conn = new OleDbConnection(connectionString))
                {
                    OleDbCommand comm = new OleDbCommand("INSERT INTO [Images] ([ID], [ImageName], [ImagePhysicalName]) VALUES (@ID, @ImageName, @ImagePhysicalName)", conn);
                    comm.Parameters.AddWithValue("@Id", id);
                    comm.Parameters.AddWithValue("@ImageName", imageName);
                    comm.Parameters.AddWithValue("@ImagePhysicalName", imagePhysicalName);
                    conn.Open();
                    comm.ExecuteNonQuery();
                    this.BindList();
                }
                
                this.BindList();
            }
            else
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "alterMsg", "alert('请选择文件!');", true);
            }
        }
    
        protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName != "Del") return;
            
            // 删除数据
            using (OleDbConnection conn = new OleDbConnection(connectionString))
            {
                OleDbCommand comm = new OleDbCommand("DELETE FROM [Images] WHERE [Id] = @Id", conn);
                comm.Parameters.AddWithValue("@Id", e.CommandArgument);
                conn.Open();
                comm.ExecuteNonQuery();
            }
    
            // 删除物理文件
            string imagePhysicalName = ((Label)e.Item.FindControl("Label3")).Text;
            string imagePhysicalPath = Path.Combine(this.ImageDirectory, imagePhysicalName);
    
            File.Delete(imagePhysicalPath);
    
            this.BindList();
        }
    </script>
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>上传文件及简单管理示例</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="btnUpload" runat="server" Text="上传" onclick="btnUpload_Click" />
        <asp:DataList ID="DataList1" runat="server" 
            onitemcommand="DataList1_ItemCommand">
            <ItemTemplate>
            <table>
                <tr>
                    <td><asp:Label ID="Label1" runat="server" Text='<%# Eval("Id") %>'></asp:Label></td>
                    <td><asp:Label ID="Label2" runat="server" Text='<%# Eval("ImageName") %>'></asp:Label></td>
                    <td><asp:Label ID="Label3" runat="server" Text='<%# Eval("ImagePhysicalName") %>'></asp:Label></td>
                    <td><asp:Image ID="Image1" runat="server" ImageUrl='<%# ImageDirectoryUrl + Eval("ImagePhysicalName") %>' /></td>
                    <td><asp:Button ID="btnDelete" CommandName="Del" CommandArgument='<%# Eval("Id") %>' OnClientClick="return confirm('您确定要删除吗?');" runat="server" Text="删除" /></td>
                </tr>
            </table>
            </ItemTemplate>
        </asp:DataList>
        </form>
    </body>
    </html>
    


    知识改变命运,奋斗成就人生!
    2009年12月28日 5:35
    版主

全部回复

  • hello.Lz

    看到不到你前台HTML无法分析,图片不显示是否路径不对,删除功能不好使,点击删除按钮触发你的事件没,你的删除按钮放在headertemplate,还是itemtemplate,还是FooterTemplate模板里了。

    参考:http://msdn.microsoft.com/zh-cn/dd279491.aspx
    2009年12月25日 10:33
  • 我的HTML的语言是:<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

    <!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 runat="server">
        <title>无标题页</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <table style="width: 766px; height: 387px">
                <tr>
                    <td style="width: 100px">
                        <asp:Image ID="Image1" runat="server" />
                        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></td>
                </tr>
                <tr>
                    <td style="width: 100px">
                        <asp:FileUpload ID="FileUpload1" runat="server" />
                        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="上传" />
                        <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="确定" /></td>
                </tr>
                <tr>
                    <td style="width: 100px">
                        <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label></td>
                </tr>
                <tr>
                    <td style="width: 100px">
                        <asp:DataList ID="DataList1" runat="server" Height="168px" RepeatColumns="4" RepeatDirection="Horizontal"
                            Width="487px" OnDeleteCommand="DataList1_DeleteCommand">
                            <ItemTemplate>
                                <asp:Image ID="Image2" runat="server" ImageUrl='<%#DataBinder.Eval(Container.DataItem,"MapNameUrl") %>' /><br />
                                <asp:Label ID="Label3" runat="server" Text='<%#  DataBinder.Eval(Container.DataItem,"MapName") %>'></asp:Label><br />
                                <asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">删除</asp:LinkButton>
                            </ItemTemplate>
                        </asp:DataList></td>
                </tr>
                <tr>
                    <td style="width: 100px">
                        <asp:Label ID="Label4" runat="server" Text="当前页面为:"></asp:Label>[<asp:Label ID="Label5"
                            runat="server" Text="1"></asp:Label>]<asp:Label ID="Label6" runat="server" Text="总页码为:"></asp:Label>[<asp:Label
                                ID="Label7" runat="server"></asp:Label>]<asp:LinkButton ID="LinkButton2" runat="server"
                                    OnClick="LinkButton2_Click">第一页</asp:LinkButton>
                        <asp:LinkButton ID="LinkButton3" runat="server" OnClick="LinkButton3_Click">上一页</asp:LinkButton>
                        <asp:LinkButton ID="LinkButton4" runat="server" OnClick="LinkButton4_Click">下一页</asp:LinkButton>
                        <asp:LinkButton ID="LinkButton5" runat="server" OnClick="LinkButton5_Click">最后一页</asp:LinkButton></td>
                </tr>
                <tr>
                    <td style="width: 100px">
                    </td>
                </tr>
            </table>
       
        </div>
        </form>
    </body>
    </html>

    删除按钮放在ITEMTEMPLATE,谢谢你给的参考资料。
    我之前已经参考过了。请你帮我分析一下问题的所在。可能是图片的路径出问题,数据库显示的路径是D:\12.19\images\091225125129,但是不知道怎样修改。
    2009年12月25日 11:28
  • 此代码只是为了演示,上传和添加数据我都写在按钮里了并做了简化,数据库表我只用了2个字段一个id,一个图片名称,图片不显示是你路径不对,删除不好使请给你的删除按钮CommandName="delete"属性,代码如下

     //增加
        protected void Button2_Click(object sender, EventArgs e)
        {
            OleDbConnection conn = new OleDbConnection(ConfigurationManager.AppSettings["connection"]);
            conn.Open();
            bool Flage=false;
            //取的上传文件扩展名
            string fileExt = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName).ToLower();
            //定义一个数字允许上传图片的扩展名
            string[] AgreeExPentFile = new string[] { ".jpg", ".jpeg", ".gif", ".bmp"};
            if (FileUpload1.HasFile)
            {
                for (int i = 0; i < AgreeExPentFile.Length; i++)
                {
                    if (fileExt.Equals(AgreeExPentFile[i]))
                    {
                       Flage = true;
                    }
                }
                if (Flage)
                {
                    //重新定义上传文件名称 例如:091221013516.jpg
                    string newfile = DateTime.Now.ToString("yyMMddhhmmss") + fileExt;
                    //讲图片上传到文件夹upload目录下
                    string webfilepath = Server.MapPath("upload/" + newfile);
                    string strSQL = "Insert Into BL_Table(b_img,b_date) Values('" + newfile + "','" + DateTime.Now + "')";
                    OleDbCommand com = new OleDbCommand(strSQL, conn);
                    com.ExecuteNonQuery();
                    FileUpload1.SaveAs(webfilepath);
                    conn.Close();
                    DBBind();//调用你的刷新方法
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), "jsalert", "alert('图片格式不正确')", true);
                    return;
                }
            }       
        }
        //删除
        protected void DataList1_DeleteCommand(object source, DataListCommandEventArgs e)
        {
            OleDbConnection conn = new OleDbConnection(ConfigurationManager.AppSettings["connection"].ToString());
            conn.Open();
            Int32 Id =Convert.ToInt32(DataList1.DataKeys[e.Item.ItemIndex]);
            string strDel = "Delete From BL_Table Where Id=" + Id;
            OleDbCommand com = new OleDbCommand(strDel, conn);
            com.ExecuteNonQuery();
            conn.Close();
            DBBind();//调用你的刷新方法
        }
    <asp:DataList ID="DataList1" runat="server" DataKeyField="id" Height="168px" OnDeleteCommand="DataList1_DeleteCommand"
            RepeatColumns="4" RepeatDirection="Horizontal" Width="687px">
            <ItemTemplate>
                <asp:Image ID="Image2" ImageUrl='<%# "upload/"+Eval("b_img") %>' runat="server" Height="100px" Width="100px" />
               <!--或者采用html标签 <img src="upload/<%# Eval("b_img") %>" alt="ToolTip" width="100px" height="100px" /> -->
                <br />
                <asp:LinkButton ID="LinkButton1" runat="server" CommandName="delete">删除</asp:LinkButton>
            </ItemTemplate>
        </asp:DataList>
    2009年12月25日 12:45
  • 十分感谢你对我问题的解答,我会努力的
    2009年12月25日 13:31
  • 你好,

    希望你已经解决了你的问题。
    如果显示图片的问题仍然没有解决,请注意你说的数据库中的图片路径为D:\12.19\images\091225125129。

    如果你直接把这个绑定到Image控件上当然不行了。你可以获得图片的名字,然后把它转换成web地址,如~/images/091225125129.jpg。
    Microsoft Online Community Support
    2009年12月28日 3:42
  • 问题还是没有解决,希望你能帮帮忙。
    这是实现上传图片和将图片相关数据插入到数据库里的代码,我觉得路径需要转换为相对路径,但是不知道如何修改
    protected void Button1_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                string name = FileUpload1.PostedFile.FileName;
                FileInfo file = new FileInfo(name);
                string filename = file.Name;
                string webfilepath = Server.MapPath("images/" + filename);
                string filecontenttype = FileUpload1.PostedFile.ContentType;
                if (filecontenttype == "image/bmp" || filecontenttype == "image/gift" || filecontenttype == "image/pjpeg")
                {
                    if (!File.Exists(webfilepath))
                    {
                        try
                        {
                            FileUpload1.SaveAs(webfilepath);
                            Label1.Visible = true;
                            Label2.Visible = true;
                            Label1.Text = "文件" + filename + "成功上传," + "文件大小为:" + FileUpload1.PostedFile.ContentLength + "字节";
                            Image1.Visible = true;
                            Image1.ImageUrl = "images/" + filename;
                            Image1.Width = 200;
                            Image1.Height = 150;
                            Label2.Text = "按200*150大小显示";
                        }
                        catch (Exception ex)
                        {
                            Label1.Visible = true;
                            Label1.Text = "文件上传失败,失败原因:" + ex.Message;
                        }
                    }
                    else
                    {
                        Label1.Visible = true;
                        Label1.Text = "文件已经存在,请重命名后上传";
                    }
                }
                else
                {
                    Label1.Visible = true;
                    Label1.Text = "文件类型不符,只能上传*.bmp,*.jpg,*.gif类型的文件";
                }
            }
            else
            {
                Label1.Visible = true;
                Label1.Text = "请选择文件或输入文件路径及名称!";
            }
        }
        protected void Button2_Click(object sender, EventArgs e)
        {
            OleDbConnection conn = new OleDbConnection();
            conn.ConnectionString = "Provider=Microsoft.Jet.OleDb.4.0;" + "Data Source=" + Server.MapPath("App_Data/eshop.mdb.mdb");
            conn.Open();
            //获取上传文件扩展名
            string fileExt = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName).ToLower();
            //重新定义上传到文件名称
            string newfile = DateTime.Now.ToString("yyMMddhhmmss") + fileExt;
            string webfilepath = Server.MapPath("~images/" + newfile);
            string strSQL = "insert into 图片(MapNameUrl,MapName,Map_SysData) values('" + webfilepath + "','" + newfile + "','" + DateTime.Now + "')";
            OleDbCommand com = new OleDbCommand(strSQL, conn);
            com.ExecuteNonQuery();
            FileUpload1.SaveAs(webfilepath);
            conn.Close();
            DBBind();

        }


    这是数据的删除功能,但是实现不了
    protected void DataList1_DeleteCommand(object source, DataListCommandEventArgs e)
        {
            OleDbConnection conn = new OleDbConnection();
            conn.ConnectionString = "Provider=Microsoft.Jet.OleDb.4.0;" + "Data Source=" + Server.MapPath("App_Data/eshop.mdb.mdb");
            conn.Open();
            Int32 Id = Convert.ToInt32(DataList1.DataKeys[e.Item.ItemIndex]);
            string strDel = "Delete From 图片 Where Map_ID=" + Id;
            OleDbCommand com = new OleDbCommand(strDel, conn);
            com.ExecuteNonQuery();
            conn.Close();
            DBBind();//调用你的刷新方法

    希望你能帮帮手。
    2009年12月28日 3:55
  • 你的image文件夹在什么位置?感觉应该是图片引用路径不对。

    2009年12月28日 4:53
  • 你好!

    针对你的情况我写了个完事的示例,你参照这个例子,修改一下你的代码。

    <%@ Page Language="C#" AutoEventWireup="true" %>
    <%@ Import Namespace="System.IO" %>
    <%@ Import Namespace="System.Data" %>
    <%@ Import Namespace="System.Data.OleDb" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <script runat="server">
    
        const string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\DB.mdb;";
        private string fImageDirectory;
        public string ImageDirectory
        {
            get
            {
                if (String.IsNullOrEmpty(fImageDirectory))
                    fImageDirectory = Server.MapPath("Images");
    
                return fImageDirectory;
            }
        }
        private string fImageDirectoryUrl;
        private string ImageDirectoryUrl
        {
            get
            {
                if (String.IsNullOrEmpty(fImageDirectoryUrl))
                    fImageDirectoryUrl = String.Format("http://{0}/Images/", Request.Url.Authority);
                
                return fImageDirectoryUrl;
            }
        }
    
        protected void Page_Load(object sender, EventArgs e)
        {
            /* 表结构
             * 表名: Images
             * ID 文本
             * ImageName 文本
             * ImagePhysicalName 文本
             */
            if (!this.IsPostBack)
                this.BindList();
        }
        
        private void BindList()
        {
            string commandText = "SELECT * FROM [Images]";
    
            using (OleDbDataAdapter da = new OleDbDataAdapter(commandText, connectionString))
            {
                DataSet ds = new DataSet();
                da.Fill(ds);
                
                this.DataList1.DataSource = ds.Tables[0];
                this.DataList1.DataBind();
            }
        }
        
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (this.FileUpload1.HasFile)
            {
                string id = Guid.NewGuid().ToString();
                string imageName = Path.GetFileName(this.FileUpload1.PostedFile.FileName);
                string imagePhysicalName = String.Format("{0}{1}", id, Path.GetExtension(imageName));
                string imagePath = Path.Combine(this.ImageDirectory, imagePhysicalName);
    
                // 保存物理文件
                this.FileUpload1.SaveAs(imagePath);
    
                // 添加数据
                using (OleDbConnection conn = new OleDbConnection(connectionString))
                {
                    OleDbCommand comm = new OleDbCommand("INSERT INTO [Images] ([ID], [ImageName], [ImagePhysicalName]) VALUES (@ID, @ImageName, @ImagePhysicalName)", conn);
                    comm.Parameters.AddWithValue("@Id", id);
                    comm.Parameters.AddWithValue("@ImageName", imageName);
                    comm.Parameters.AddWithValue("@ImagePhysicalName", imagePhysicalName);
                    conn.Open();
                    comm.ExecuteNonQuery();
                    this.BindList();
                }
                
                this.BindList();
            }
            else
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "alterMsg", "alert('请选择文件!');", true);
            }
        }
    
        protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName != "Del") return;
            
            // 删除数据
            using (OleDbConnection conn = new OleDbConnection(connectionString))
            {
                OleDbCommand comm = new OleDbCommand("DELETE FROM [Images] WHERE [Id] = @Id", conn);
                comm.Parameters.AddWithValue("@Id", e.CommandArgument);
                conn.Open();
                comm.ExecuteNonQuery();
            }
    
            // 删除物理文件
            string imagePhysicalName = ((Label)e.Item.FindControl("Label3")).Text;
            string imagePhysicalPath = Path.Combine(this.ImageDirectory, imagePhysicalName);
    
            File.Delete(imagePhysicalPath);
    
            this.BindList();
        }
    </script>
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>上传文件及简单管理示例</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="btnUpload" runat="server" Text="上传" onclick="btnUpload_Click" />
        <asp:DataList ID="DataList1" runat="server" 
            onitemcommand="DataList1_ItemCommand">
            <ItemTemplate>
            <table>
                <tr>
                    <td><asp:Label ID="Label1" runat="server" Text='<%# Eval("Id") %>'></asp:Label></td>
                    <td><asp:Label ID="Label2" runat="server" Text='<%# Eval("ImageName") %>'></asp:Label></td>
                    <td><asp:Label ID="Label3" runat="server" Text='<%# Eval("ImagePhysicalName") %>'></asp:Label></td>
                    <td><asp:Image ID="Image1" runat="server" ImageUrl='<%# ImageDirectoryUrl + Eval("ImagePhysicalName") %>' /></td>
                    <td><asp:Button ID="btnDelete" CommandName="Del" CommandArgument='<%# Eval("Id") %>' OnClientClick="return confirm('您确定要删除吗?');" runat="server" Text="删除" /></td>
                </tr>
            </table>
            </ItemTemplate>
        </asp:DataList>
        </form>
    </body>
    </html>
    


    知识改变命运,奋斗成就人生!
    2009年12月28日 5:35
    版主
  • 多谢你的示例,,但可以加一些注析吗,有些我看不懂,而且是第一次接触。谢谢。
    2009年12月28日 11:15
  • 不懂的地方可以提出来嘛!
    知识改变命运,奋斗成就人生!
    2009年12月29日 1:02
    版主