How to show result of a query in MessageBox - c#

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.

Related

C# windows application error " Input string was not in a correct format"

I am creating a Windows application form using C# and MSSql Database. There is a form named Discard Item and have two combobox. One for Location and second for Place. I have created a function to get Location in combobox from the database and it is working fine. Now, on Location_SelectedIndexChanged event I need to fill Places in combobox with Location ID and for that I have written the code as shown below, but I am receiving an error "Input was not in a correct format" when I run the program.
I have tried Int32.Parse method and Convert.Toint32 method but still getting the error.
private void comDiscardLocation_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDBconnectionString"].ToString()))
{
con.Open();
SqlCommand cmd = new SqlCommand("GetWSPlace", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Location_Id", Int32.Parse(comDiscardLocation.SelectedValue.ToString()));
SqlDataReader rd;
rd = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rd);
comDiscardPlace.DataSource = dt;
comDiscardPlace.ValueMember = "Place_ID";
comDiscardPlace.DisplayMember = "Place_Name";
comDiscardPlace.Text = "--------Select--------";
Please help me to remove this error.

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...

Save and retrive rtf text from database using 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.

Bringing up pictures from a database as I search for the name

I need help with this program I'm trying to write. I'm a complete noob at this, so forgive my shortcomings but I'm trying to create a search feature, in which it completes the names from a database as soon as you write the first letter. I've done this succesfully, now I have to bring up pictures also from the same database, I'm getting some errors. Could you take a look at my code and tell me what's wrong? And also is this enough?
note: My aim is to bring up pictures AS they write the name.
void showpic(string queryStr)
{
SqlConnection conn = new SqlConnection(#"server adress");
conn.Open();
SqlCommand execute = new SqlCommand("SELECT Pernr from View_PhoneBook where DisplayName=" + textBox1.Text, conn);
try
{
StringCollection View_Phonebook = new StringCollection();
SqlDataReader reader = execute.ExecuteReader();
while (reader.Read())
{
View_Phonebook.Add(reader.GetString(0));
}
pictureBox1.ImageLocation.Equals("url" + View_Phonebook + ".jpg");
}
catch (Exception ex)
{
}
conn.Close();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
showpic(textBox1.Text);
}
Add quotes to the string in this line, like so:
SqlCommand execute = new SqlCommand('SELECT Pernr from View_PhoneBook where DisplayName= #text', conn);
execute.Parameters.Add("text", SqlDbType.Text).Value = Textbox1.text;
I will suggest, you should do this using a StoredProc.
Its not a solution to the prob, but another way to do this.
That way you will not face any such probs.
Moreover, havign a StoredProc is better then constructing a query on every text change event.

error in connecting combox to textbox with database

i am working on C# .net platform
i wanted to connect my combox to my text box
this is code done by me but it is give me error
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
panel1.Visible = true;
string sql;
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "Data Source=CJ\SQLEXPRESS;Initial Catalog=elligiblity;Persist Security Info=True;User ID=sa;Password=123";
cn.Open();
sql = "SELECT inst_name FROM institude WHERE(inst_id="+comboBox2.SelectedItem+")";
SqlCommand cmd = new SqlCommand(sql,cn);
SqlDataReader myReader = cmd.ExecuteReader();
while(myReader.Read())
{
textBox2.Text = myReader["inst_name"].ToString();
}
myReader.Close();
cn.Close();
The multi-part identifier "System.Data.DataRowView" could not be bound.
on this line of the code
SqlDataReader myReader = cmd.ExecuteReader();
As well as that problem there are a few issues with your code that you might want to bear in mind.
Firstly, if there is an error between opening and closing the connection (as indeed there was) then you're probably going to leave connections open. Eventually this will choke your site. Use
using (SqlConnection cn = new SqlConnection())
{
}
when you're out of the scope of the using statement the connection will be closed and disposed of.
Also, you probably want to parameterize your query (for reasons both of security and efficiency), so that it is
sql = "SELECT inst_name FROM institude WHERE(inst_id=#inst_id)";
Then add that parameter to your command object and set its value to your combo box selected item value.
You want
comboBox2.SelectedValue
or
comboxBox2.SelectedItem.ToString()
then but I'd look at using parameters instead as that's not a very good way of creating a SQL string.
Also, do you realise that if you return more than one result your textbox2 will only show the last result as its text will get over-ridden with each result as its read?
First of all check the binding of dropdown. If you are binding datasource with ID and Text something like this combobox2.DisplayMember ="Name"; combobox2.ValueMember ="ID". After that you have to check for the parameter to be used in your query if its text then try combobox2.text else if you are selecting on the basis of id use int.parse(combobox2.selectedvalue) or simply combobox2.selectedvalue if your id is alphanumeric.

Categories

Resources