Save text in RichTextBox to SQL Server (C #)

Source: Internet
Author: User
Tags int size
Server Save:

private void Btnsave_click (object sender, System.EventArgs e)
{

FileStream stream = null;
SqlConnection conn = null;
SqlCommand cmd = null;
Try
{
Richtextbox1.savefile ("Temp.rtf");
stream = new FileStream ("Temp.rtf", FileMode.Open, FileAccess.Read);
int size = Convert.ToInt32 (stream. Length);
byte[] rtf = new Byte[size];
Stream. Read (RTF, 0, size);

conn = new SqlConnection ("database=northwind;integrated security=true;");
Conn. Open ();
cmd = new SqlCommand ("UPDATE Employees SET photo= @Photo WHERE employeeid=1", conn);

SqlParameter paramrtf =
New SqlParameter ("@Photo",
Sqldbtype.image,
Rtf. Length,
ParameterDirection.Input,
False
0,0,null,
DataRowVersion.Current,
RTF);
Cmd. Parameters.Add (PARAMRTF);

int rowsupdated = Convert.ToInt32 (cmd. ExecuteNonQuery ());

MessageBox.Show (String.Format ("{0} rows updated", rowsupdated));
}
catch (Exception ex)
{
MessageBox.Show (ex. message);
}
Finally
{
if (stream!= null) stream. Close ();
if (cmd!= null) cmd. Parameters.clear ();
IF (conn!= NULL) conn. Close ();
}
}

Read:

private void Btnload_click (object sender, System.EventArgs e)
{
Richtextbox1.clear ();

SqlConnection cn = NULL;
SqlCommand cmd = null;
SqlDataReader reader = null;
Try
{
cn = New SqlConnection ("database=northwind;integrated security=true;");
cn. Open ();
cmd = new SqlCommand ("Select Photo from Employees WHERE employeeid=1", CN);
reader = cmd. ExecuteReader ();
Reader. Read ();
if (reader. HasRows)
{
if (!reader. IsDBNull (0))
{
byte[] rtf = new Byte[convert.toint32 (reader. GetBytes (0, 0, NULL, 0, Int32.MaxValue))];
Long bytesreceived = reader. GetBytes (0, 0, RTF, 0, RTF. Length);

ASCIIEncoding encoding = new ASCIIEncoding ();
Richtextbox1.rtf = Encoding. GetString (RTF, 0, Convert.ToInt32 (bytesreceived));
}
}
}
catch (Exception ex)
{
MessageBox.Show (ex. message);
}
Finally
{
if (reader!= null) reader. Close ();
if (CN!= null) CN. Close ();
}

}



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.