文本框中的值没有插入数据库c#

本文关键字:插入 数据库 文本 | 更新日期: 2023-09-27 18:03:27

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            if (Request.InputStream.Length > 0)
            {
                using (StreamReader reader = new StreamReader(Request.InputStream))
                {
                    string hexString = Server.UrlEncode(reader.ReadToEnd());
                    string imageName = DateTime.Now.ToString("dd-MM-yy hh-mm-ss");
                    string imagePath = string.Format("~/losefound/{0}.png", imageName);
                    string ItemName = txtItemName.Text;
                    string Place = txtPlace.Text;
                    byte[] bytes = ConvertHexToBytes(hexString);
                    File.WriteAllBytes(Server.MapPath(imagePath), bytes);
                    string VisitorManagementConnectionString = ConfigurationManager.ConnectionStrings["VisitorManagementConnectionString"].ConnectionString;
                    using (SqlConnection con = new SqlConnection(VisitorManagementConnectionString))
                    {
                        string query = "INSERT INTO LostFound (ItemName, FoundAt, TimeIn, ImageName, ContentType, Data) VALUES(@ItemName, @FoundAt, @TimeIn, @ImageName, @ContentType, @Data);SELECT SCOPE_IDENTITY()";
                        using (SqlCommand cmd = new SqlCommand(query))
                        {
                            cmd.Connection = con;
                            cmd.Parameters.AddWithValue("@ItemName", ItemName);
                            cmd.Parameters.AddWithValue("@FoundAt", Place);
                            cmd.Parameters.AddWithValue("@TimeIn", DateTime.Now);
                            cmd.Parameters.AddWithValue("@ImageName", imageName);
                            cmd.Parameters.AddWithValue("@ContentType", "image/png");
                            cmd.Parameters.AddWithValue("@Data", bytes);
                            con.Open();
                            Session["CapturedImageId"] = cmd.ExecuteScalar();
                            con.Close();
                        }
                    }
                }
            }
        }
    }
    private static byte[] ConvertHexToBytes(string hex)
    {
        byte[] bytes = new byte[hex.Length / 2];
        for (int i = 0; i < hex.Length; i += 2)
        {
            bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
        }
        return bytes;
    }
    [WebMethod(EnableSession = true)]
    public static string GetCapturedImage()
    {
        string url = string.Empty;
        int imageId = Convert.ToInt32(HttpContext.Current.Session["CapturedImageId"]);
        string VisitorManagementConnectionString = ConfigurationManager.ConnectionStrings["VisitorManagementConnectionString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(VisitorManagementConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "SELECT Data FROM LostFound WHERE Id = @Id";
                cmd.Parameters.AddWithValue("@Id", imageId);
                cmd.Connection = con;
                con.Open();
                byte[] bytes = (byte[])cmd.ExecuteScalar();
                url = "data:image/png;base64," + Convert.ToBase64String(bytes, 0, bytes.Length);
                con.Close();
            }
        }
        HttpContext.Current.Session["CapturedImageId"] = null;
        return url;
    }
    protected void btnCapture_Click(object sender, EventArgs e)
    {
    }
}

文本框中的值从未插入到数据库中。只有datetime。现在,可以插入imageName、contentType和data了。应该在btncapture中插入文本框查询吗?

有人可以引导我哪里我错了?

文本框中的值没有插入数据库c#

此代码应该至少出现在按钮单击中。

在asp.net页面事件生命周期中调用page_load事件时,文本框将被清除。

只有当不是回发时才会提交给DB。

if (!this.IsPostBack)

由于您只在Page_Load中运行此操作,因此文本字段可能没有任何用户输入,因此为空白。你也可以在PostBack上做。

if (this.IsPostBack)
{
    // Do stuff
}

或者,更好的做法是,按照Jeremy Thompson的建议,在用户单击按钮时分配一个事件处理程序。在Page_Load中做这种逻辑经常会回来困扰你。当其他开发人员添加UpdatePanel或其他回发事件时会发生什么?然后,该代码将在每次回发时运行。它的规模不是很好。似乎你已经得到了这个事件处理程序- btnCapture_Click,我建议你使用它。

的例子:

在你的HTML中:

<asp:Button ID="Button1" runat="server" onclick="btnCapture_Click" Text="Button" />  

在你的CS中:

protected void btnCapture_Click(object sender, EventArgs e)
{
    if (Request.InputStream.Length > 0)
        {
            using (StreamReader reader = new StreamReader(Request.InputStream))
            {
                string hexString = Server.UrlEncode(reader.ReadToEnd());
                string imageName = DateTime.Now.ToString("dd-MM-yy hh-mm-ss");
                string imagePath = string.Format("~/losefound/{0}.png", imageName);
                string ItemName = txtItemName.Text;
                string Place = txtPlace.Text;
                byte[] bytes = ConvertHexToBytes(hexString);
                File.WriteAllBytes(Server.MapPath(imagePath), bytes);
                string VisitorManagementConnectionString = ConfigurationManager.ConnectionStrings["VisitorManagementConnectionString"].ConnectionString;
                using (SqlConnection con = new SqlConnection(VisitorManagementConnectionString))
                {
                    string query = "INSERT INTO LostFound (ItemName, FoundAt, TimeIn, ImageName, ContentType, Data) VALUES(@ItemName, @FoundAt, @TimeIn, @ImageName, @ContentType, @Data);SELECT SCOPE_IDENTITY()";
                    using (SqlCommand cmd = new SqlCommand(query))
                    {
                        cmd.Connection = con;
                        cmd.Parameters.AddWithValue("@ItemName", ItemName);
                        cmd.Parameters.AddWithValue("@FoundAt", Place);
                        cmd.Parameters.AddWithValue("@TimeIn", DateTime.Now);
                        cmd.Parameters.AddWithValue("@ImageName", imageName);
                        cmd.Parameters.AddWithValue("@ContentType", "image/png");
                        cmd.Parameters.AddWithValue("@Data", bytes);
                        con.Open();
                        Session["CapturedImageId"] = cmd.ExecuteScalar();
                        con.Close();
                    }
                }
            }
        }
}  

如果你在绑定按钮时遇到麻烦,你可以看看这个问题。

首先,检查你的aspx声明中是否有AutoEventWireup="true"

您也可以尝试手动分配委托。

btnCapture += new EventHandler(btnCapture_Click);