textBox中的值未插入数据库C#

时间:2016-08-22 08:26:44

标签: c# asp.net database insert add

    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.now,imageName,contentType和数据。 应该在btncapture上插入文本框查询吗?

有人可以指导我哪里出错了吗?

2 个答案:

答案 0 :(得分:0)

此代码应至少按下按钮。

asp.net page event life cycle中调用page_load事件时,TextBox会被清除。

答案 1 :(得分:0)

如果不是回发,则只提交给数据库。

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();

                    }
                }
            }
        }
}  

如果您无法绑定按钮,可以查看this question

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

您也可以尝试手动分配代理。

btnCapture += new EventHandler(btnCapture_Click);