Save and retrive rtf text from database using c# - c#

I just finished to save a text from a richtextbox into sql database. Here you have the code:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=MARIA-PC;Initial Catalog=Account;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[FISIER] (File_name,The_text) VALUES (#File_name,#The_text)", con);
cmd.Parameters.Add("#File_name", textBox1.Text);
cmd.Parameters.AddWithValue("#The_text", richTextBox1.Rtf);
cmd.ExecuteNonQuery();
con.Close();
}
Here is the table Click here for table
Now, my problem is that I don't know how to retrive the text from the database. As you see there the text I had saved into The_text and the data type is Text. I want to retrive the data back into richtextbox.

A quick search would have revealed the answer to this. For example, here is some sample code that queries a database table...
// 1. Instantiate a new command with a query and connection
SqlCommand cmd = new SqlCommand("select CategoryName from Categories", conn);
// 2. Call Execute reader to get query results
SqlDataReader rdr = cmd.ExecuteReader();
You can change the table name and fields to match your database.
This code was found at http://www.csharp-station.com/Tutorial/AdoDotNet/Lesson03, but there are millions of other sites that will teach you this stuff.

Related

unable to insert data in sql database with c# even no error accur

hy I want to insert new record in my database but am unable to do this even code is fully error free, I added following code in my button click event
here is my code
SqlConnection con= new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated Security=true;");
SqlCommand cmd;
SqlDataAdapter adapt;
private void btn_Update_Click(object sender, EventArgs e)
{
string query="insert into users(Name,Password)values('ubaid','ali')";
cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated Successfully");
con.Close();
}
I mean insert query is not updating my database, even when I execute my query it return 2 not 0 which means query applied successfully,
not really an answer but the steps you need to take to see whats going on, so we can help you are a bit longer...
you will need to execute the following query, once in your sql management studio, and once in your program ... i suspect the result being different in both cases
select ##SERVERNAME, ##SERVICENAME, db_name(), SCHEMA_NAME()
on the code side please use this:
private void btn_Update_Click(object sender, EventArgs e)
{
// string query="insert into users(Name,Password)values('ubaid','ali')";
// cmd = new SqlCommand(query, con);
// con.Open();
// cmd.ExecuteNonQuery();
// MessageBox.Show("Record Updated Successfully");
// con.Close();
string query="select ##SERVERNAME, ##SERVICENAME, db_name(), SCHEMA_NAME()";
cmd = new SqlCommand(query, con);
con.Open();
using(var rdr = cmd.ExecuteReader())
{
rdr.read();
MessageBox.Show($"{rdr.GetString(0)}, {rdr.GetString(1)}, {rdr.GetString(2)}, {rdr.GetString(3)} ");
}
con.Close();
}
the result should show the name of the server, its instance name, the name of your DB and of the default schema you are using in both cases
example result for my testmachine would look like this:
srv9, MSSQLSERVER, testdb, dbo
expectation in your case:
you will get 2 different results which means that your sql management studio, where you are trying to check if your code did the right thing, is using a different server, instance, database or schema
with the provided information it will be possible to change the used connectionstring so both your clients work on the same database...

How to show result of a query in MessageBox

I want to show result of a query in a MessageBox in C#, but the code below doesn't work.
private void button26_Click(object sender, EventArgs e)
{
string constring =
#"Data Source=blahblahblah;user id=blah;password=blah;database=blah;";
SqlConnection con = new SqlConnection(constring);
SqlCommand check = new SqlCommand("select blah from blah where blah=#blah");
check.Parameters.AddWithValue("#blah", textBox1.Text);
con.Open();
string gholi = check.ExecuteScalar().ToString();
con.Close();
MessageBox.Show(gholi);
}
I think best way to see result of code, run application and set breakpoint in first line code.
if you want the next step press F10.
you can see the relevant details with debug code.
You should sql reader to read data from data base or you can use dataset to retrive data from database and then trying display in message box.

Update query isn't updating records in database?

private void btnUpdate_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
OleDbCommand cmd = new OleDbCommand("Update tb1 set rollno=#rollno WHERE name=#Name", con);
cmd.Parameters.AddWithValue("#Name", txtproject_name.Text);
cmd.Parameters.AddWithValue("#rollno", textroll.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Updated sucessfully");
}
This is my code for updating data in the database but it is not updating anything... why isn't it working?
Do not use named parameters, use ? instead.
MSDN:
The OLE DB .NET Provider does not support named parameters for passing
parameters to an SQL statement or a stored procedure called by an
OleDbCommand when CommandType is set to Text. In this case, the
question mark (?) placeholder must be used. For example:
SELECT * FROM Customers WHERE CustomerID = ?
Therefore, the order in which OleDbParameter objects are added to the
OleDbParameterCollection must directly correspond to the position of
the question mark placeholder for the parameter in the command text.
Which database server you are using? there is difference passing parameters while server changes for example
SQL Server - #Name
MySql - #Name
Oracle - :Name
etc.
if you are using MS Access use as follows
private void btnUpdate_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
OleDbCommand cmd = new OleDbCommand("Update tb1 set rollno=? WHERE name=?", con);
cmd.Parameters.AddWithValue("rollno", textroll.Text);
cmd.Parameters.AddWithValue("name", txtproject_name.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Updated sucessfully");
}
for more refer
http://www.mikesdotnetting.com/Article/26/Parameter-Queries-in-ASP.NET-with-MS-Access

C# ASP.NET TSQL Code Behind Upgrade DB

I'm trying to upgrade the db from users' input, but it doesn't work...
I'm using this:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand();
SqlCommand ncmd = new SqlCommand("Update Utenti Set Nome = #vnome where [Indirizzo E-Mail]=#vem", con);
ncmd.Parameters.AddWithValue("#vem", Session["[Indirizzo E-Mail]"].ToString());
ncmd.Parameters.AddWithValue("#vnome", TextBox2.Text);
ncmd.Connection = con;
con.Open();
ncmd.ExecuteNonQuery();
con.Close();
Label2.Text = "Dati aggiornati con successo!";
Response.Redirect("~/ModificaDati.aspx");
}
When I click on the button it show me the Label2 text, but in the database the "Nome" is not changed, why?
Thanks before for the answers ^^
I would change your method as below
if (Session["[Indirizzo E-Mail]"] != null &&
!string.IsNullOrEmpty(Session["[Indirizzo E-Mail]"].ToString()) &&
!string.IsNullOrEmpty(TextBox2.Text))
{
string vem = Session["[Indirizzo E-Mail]"].ToString();
using (var con = new SqlConnection(strcon))
using (var ncmd = new SqlCommand("Update Utenti Set Nome = #vnome where [Indirizzo E-Mail]=#vem", con))
{
con.Open();
ncmd.Parameters.AddWithValue("#vem", vem);
ncmd.Parameters.AddWithValue("#vnome", TextBox2.Text);
int rows = ncmd.ExecuteNonQuery();
Label2.Text = rows + " Dati aggiornati con successo!";
}
}
Response.Redirect("~/ModificaDati.aspx");
Added input validation, session values can be null, better to check before you update database
when you create SqlCommand you can give the connection, no need to set it again
make sure your SQL is valid
use using statements for disposable objects like SqlConnection, SqlCommand
Your code looks ok. Just make sure you check if SQL is correct as Damith already suggested.
Another thing I’s recommend is additionally validating your parameters for data type correctness before executing the query.
Using this approach you’ll probably avoid a lot of unnecessary exceptions and also be able to provide more user friendly messages. Of course this only applies if user input is non text type
//Data Type verification
DateTime tmp;
if (!DateTime.TryParse(Label2.Text.Trim(), out tmp))
{
//Show error message that this is not a correct data type
}
Open your connection first
con.Open();
ncmd.Connection = con;
Hope it helps

How to refresh database through c sharp coding in dot net

I am developing a windows project in dot net using c sharp language and the back-end is sql server database.
What I am doing is that there is a SQL query to insert data in the table as
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source = ...........";
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO TableName(column1, column2) VALUES(txtBox1, txtBox2)", con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
Dataset ds = new Dataset();
Now, what problem I am facing here is that when I try to access this table in another windows form using Microsoft Report Viewer. Then, there the data newly inserted is not accessible since it needs the database to be refreshed.
Please tell me how can I resolve this problem.
Thanks in advance
Deepak
i don't think that you need to refresh it, just request it from db and commit transaction if you are using it. But if you want to share data between your forms use Registry pattern to achieve this.
Registry is class which will hold data for you, and you can access it from anywhere but use static variables and methods.
public class Registry
{
public static DataTable Users;
}
And if you change data from one form all forms will have updated data.
It seems there are many error,change this line
SqlCommand cmd = new SqlCommand("INSERT INTO TableName(column1, column2) VALUES(txtBox1, txtBox2)", con);
to
SqlCommand cmd = new SqlCommand(String.format("INSERT INTO TableName(column1, column2) VALUES('{0}', '{1}')",txtBox1.Text,txtBox2.Text), con);
and your command never executed on database

Categories

Resources