【问题标题】:Fill Data Table with image data as byte array in C#在 C# 中用图像数据作为字节数组填充数据表
【发布时间】:2023-03-18 08:07:01
【问题描述】:

所以我已经填写了数据表,但我需要图像数据的列不起作用。我可以看到表格已填满,可以看到它正在读取数据,但不是字节数组,也不是显示图像。

public void Bindformview()
    {
        try
        {
            SqlDataAdapter adp = new SqlDataAdapter("Select * from Recipes", con);
            DataTable dt = new DataTable();

            adp.Fill(dt);

            if (dt.Rows.Count > 0)
            {
                FormViewRecipes.DataSource = dt;
                FormViewRecipes.DataBind();
            }
            else
            {
                FormViewRecipes.DataSource = null;
                FormViewRecipes.DataBind();
            }
        }

而且我知道我需要插入此代码或类似的代码,将数据作为字节流从 db“thumbnail varbinary(MAX)”列中提取出来,以获取图像正确显示的字节数组:

 DataColumn column = new DataColumn("MyImage"); //Create the column.
column.DataType = System.Type.GetType("System.Byte[]"); //Type byte[] to store image bytes.
column.AllowDBNull = true;
column.Caption = "My Image";

table.Columns.Add(column); //Add the column to the table.

还有这个:

 DataRow row = table.NewRow();
row["MyImage"] = <Image byte array>;
tables.Rows.Add(row);

但我不需要新列或新行,因为这些字段已经存在。 那么如何在数据表中填充“Thumbnail”列,并显示字节数组数据,以及在加载 dt 的 if 语句之前,在绑定 dt 的 if 语句中,我在哪里插入所述代码?

我是否通过这样声明列来做到这一点:

dt.column.thumbnail.fill(byte[] bytes = (byte[])cmd.ExecuteScalar());

然后像这样把这个填入formview image1 ID?

                    string strBase64 = Convert.ToBase64String(bytes);
                    formviewrecipes.Image1.ImageUrl = "data:Image/png;base64," + strBase64;

我只是处于停顿状态,不知道该怎么做。 需要明确的是,我已经拥有带有正确图像信息的数据库,并且可以通过&lt;asp:image id=image1...etc /&gt; 显示它,以及使用此代码在表单视图之外检索图像的其他代码,

string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                using (SqlConnection con = new SqlConnection(cs))
                {
                    SqlCommand cmd = new SqlCommand("spGetImageByID", con);
                    cmd.CommandType = CommandType.StoredProcedure;

                    SqlParameter paramId = new SqlParameter()
                    {
                        ParameterName = "@Id",
                        Value = Request.QueryString["Id"]
                    };
                    cmd.Parameters.Add(paramId);
                    con.Open();
                    byte[] bytes = (byte[])cmd.ExecuteScalar();

                    string strBase64 = Convert.ToBase64String(bytes);
                    Image1.ImageUrl = "data:Image/png;base64," + strBase64;
                }
            }

但它在&lt;asp:FormView...etc/&gt; 中不起作用,我需要能够让它这样做以进行页面格式化。 这就是为什么我要朝这个方向前进,即现在使用数据表。如果您有更好的解决方案,我愿意尝试,只要它可以在 &lt;asp:formview /&gt; 元素内使用。谢谢。

【问题讨论】:

    标签: c# asp.net arrays sql-server datatable


    【解决方案1】:

    所以我想通了:

    我需要在数据绑定o = dt.Rows[0]["RecipeId"]; 之后添加一个Object o; 和这一行

    像这样:

    if (dt.Rows.Count > 0)
                    {
                        FormViewRecipes.DataSource = dt;
                        FormViewRecipes.DataBind();
                        //lblDataTable.Text = dt.Rows.Count.ToString(); ---Used for testing-
                        o = dt.Rows[0]["RecipeId"];
    
                    }
                    else
                    {
                        FormViewRecipes.DataSource = null;
                        FormViewRecipes.DataBind();
                    }
                }
    

    并按如下方式调用加载图像:

     string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                using (SqlConnection con = new SqlConnection(cs))
                {
                    SqlCommand cmd = new SqlCommand("RETRIEVE_RECIPE", con);
                    cmd.CommandType = CommandType.StoredProcedure;
    
                    SqlParameter paramId = new SqlParameter()
                    {
                        ParameterName = "@RecipeId",
                        Value = o //Object from the datatable
    
                };
                    cmd.Parameters.Add(paramId);
                    con.Open();
                    byte[] bytes = (byte[])cmd.ExecuteScalar();
    
                    if (bytes != null)
                    {
                        string strBase64 = Convert.ToBase64String(bytes);
                        Image1.ImageUrl = "data:Image/png;base64," + strBase64;
                    }
                    else
                    {
                        Image1.ImageUrl = "~/images/NoImageAvail.jpg";
                    }
                }
    

    如果其他人需要做同样的事情,这里是下面的代码。我将组合一个 for/while 或 for/next 用于同时显示多个数据库条目,而不是当前在此 &lt;asp:forview...&gt;&lt;/formview&gt; 元素设置中一次显示一个。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Configuration;
    using System.Data;
    using System.IO;
    using System.Data.SqlClient;
    
    namespace DB_Test1
    {
        public partial class Search_Results_1 : System.Web.UI.Page
        {
            string b;
            Object o;
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
            protected void Page_Load(object sender, EventArgs e)
            {
                if (Request.QueryString["Search"] != null)
                {
                    if (Request.QueryString["Text"] != null)
                    {
                        string a = Request.QueryString["Text"];
                        b = a;
                        recipeSearch(a);
                    }
                }
            }
            protected void recipeSearch(string a)
            {
                //Search the database
                con.Open();
                try
                {
                    SqlDataAdapter adp = new SqlDataAdapter("SELECT * FROM Recipes WHERE Type LIKE '%" + a + "%'", con);
                    DataTable dt = new DataTable();
    
                    adp.Fill(dt);
    
                    if (dt.Rows.Count > 0)
                    {
                        FormViewRecipes.DataSource = dt;
                        FormViewRecipes.DataBind();
                        //lblDataTable.Text = dt.Rows.Count.ToString(); ---Used for testing-
                        o = dt.Rows[0]["RecipeId"];
    
                    }
                    else
                    {
                        FormViewRecipes.DataSource = null;
                        FormViewRecipes.DataBind();
                    }
                }
    
                catch (Exception ex)
                {
                    //throw new ApplicationException("operation failed!", ex);
                }
                con.Close();
                FormViewRecipes.Visible = true;
    
                string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                using (SqlConnection con = new SqlConnection(cs))
                {
                    SqlCommand cmd = new SqlCommand("RETRIEVE_RECIPE", con);
                    cmd.CommandType = CommandType.StoredProcedure;
    
                    SqlParameter paramId = new SqlParameter()
                    {
                        ParameterName = "@RecipeId",
                        Value = o //Object from the datatable
    
                };
                    cmd.Parameters.Add(paramId);
                    con.Open();
                    byte[] bytes = (byte[])cmd.ExecuteScalar();
    
                    if (bytes != null)
                    {
                        string strBase64 = Convert.ToBase64String(bytes);
                        Image1.ImageUrl = "data:Image/png;base64," + strBase64;
                    }
                    else
                    {
                        Image1.ImageUrl = "~/images/NoImageAvail.jpg";
                    }
                }
    
                Image1.Visible = true;
    
    
            }
            protected void FormViewRecipes_PageIndexChanging(object sender, FormViewPageEventArgs e)
            {
                string a = b;
                FormViewRecipes.PageIndex = e.NewPageIndex;
                recipeSearch(a);
            }
        }
    }
    

    这是 ASPX 页面代码:

    <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
    
        <hr />
        <div class="row">
            <div class="col-md-8">
                <table>
                    <tr>
                        <td>
                            <asp:Image ID="Image1" runat="server" visable="false" Height="150px" Width="150px"/>
                        </td>
                        <td>
                            <asp:FormView ID="FormViewRecipes" runat="server" DataKeyNames="RecipeId" AllowPaging="True"
                onpageindexchanging="FormViewRecipes_PageIndexChanging" Visible="false">
                 <%--<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <RowStyle BackColor="#EFF3FB" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />--%>
                <ItemTemplate>
                <table style="border:1px solid #c1c1c1;">
                <tr style="background-color:white;font-weight:bold"><td><%--Recipe Detail--%></td><td>
                    <%--<asp:Image id="Image1" runat="server" ImageUrl='<%# Eval("Thumbnail") %>' 
                       AlternateText='<%# Eval("ThumbnailAltTxt") %>' 
                        Height="100px" Width="100px" />--%></td>
                </tr>
                  <tr><td><b>Title:- </b></td><td>
                      <asp:Label ID="lblRecipeTitle" runat="server" Text='<%# Eval("Title") %>'></asp:Label></td></tr>
                  <tr><td><b>Ingredients:- </b></td><td>
                      <asp:Label ID="lblIngredients" runat="server" Text='<%# Eval("Ingredients") %>'></asp:Label></td></tr>                
                  <tr><td><b>Directions:- </b></td><td>
                      <asp:Label ID="lblDirections" runat="server" Text='<%# Eval("Directions") %>'></asp:Label></td></tr>
                    <tr><td><b>Notes:- </b></td><td>
                      <asp:Label ID="Label1" runat="server" Text='<%# Eval("Notes") %>'></asp:Label></td></tr>
    
                                </table>
                </ItemTemplate>
                  <EmptyDataTemplate>
                <table style="border:1px solid #c1c1c1;">
                <tr style="background-color:#E5E5FE;font-weight:bold"><td><b>Recipe</b></td></tr>
                <tr><td><b>Recipe Title:-</b></td><td style="color:Red;">No Records Aviable!</td></tr>
                <tr><td><b>Recipe Ingredients:-</b></td><td style="color:Red;">No Records Aviable!</td></tr>
                <tr><td><b>Recipe Directions:-</b></td><td style="color:Red;">No Records Aviable!</td></tr>
    
                </table>
                </EmptyDataTemplate>
    
    
    
    
                </asp:FormView>
                        </td>
                    </tr>
                </table>
            </div>
            <div class="col-md-4">
                <p>Ad Space</p>
                <asp:Label ID="lblDataTable" runat="server"></asp:Label>
            </div>
        </div>
    
    </asp:Content>
    

    请记住,我注释掉了 &lt;Asp:formview.../&gt; 元素中的 &lt;asp:image..../a&gt; 元素字段,并重置了我的页面布局以获得我想要的测试结果。

    【讨论】:

    • 另外,如果您想完成这项工作并显示所有需要的项目,请将连接字符串更改为 ("Select * From DB", con) 和 o=dt.row[0],["RecipeId "] 到 "o = FormViewArticles.DataKey.Value;" - 它允许您循环浏览 dt 中的项目,而不仅仅是每次去获取 dt 中的第一个项目并获取相应文章的图像。事实上我会使用“o = FormViewArticles.DataKey.Value;”从头开始。稍微调整一下。
    猜你喜欢
    • 2017-09-06
    • 2015-07-07
    • 2014-10-23
    • 2015-06-20
    • 2011-02-02
    • 2013-11-12
    • 1970-01-01
    • 2014-06-16
    • 1970-01-01
    相关资源
    最近更新 更多