How do I print SQL query using MessageBox in C# - sql

I am stuck with this problem since yesterday. I have created a button, which when clicked display the results from a SQL Server table. I thought of using MessageBox to print these results or if there is any other way to print results?
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection("Data Source=FAREEDH;Initial Catalog=DeakinsTrade;Integrated Security=True");
SqlCommand command = new SqlCommand("SELECT * FROM Products", con);
con.Open();
SqlDataReader reader = command.ExecuteReader();
command.ExecuteNonQuery();
con.Close();
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}
I have tried different methods but it never worked.. I am really stuck. If you want more details, let me know. Thanks for the help in advance

Add a datagridview control to show multiple rows and try this code and rename it what you want and replace this YourDataGridVeiwName from the name you set for datagridview control and try below code
private void button1_Click(object sender, EventArgs e)
{
try
{
string connectionString = "Data Source=FAREEDH;Initial Catalog=DeakinsTrade;Integrated Security=True";
string query = "SELECT ProductName FROM Products;";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, con))
{
con.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(command))
{
DataTable dt = new DataTable();
sda.Fill(dt);
YourDataGridVeiwName.DataSource= dt;
}
con.Close();
}
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}

You need to use the SqlDataReader and iterate over the rows returned, extract what you need from each row, and then display that to the enduser.
I modified your code a bit, to make it safer (using blocks!), and I modified the query to return only the product name (assuming you have that) since you cannot really display a whole row in a message box....
private void button1_Click(object sender, EventArgs e)
{
try
{
string connectionString = "Data Source=FAREEDH;Initial Catalog=DeakinsTrade;Integrated Security=True";
string query = "SELECT ProductName FROM Products;";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, con))
{
con.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string productName = reader.GetFieldValue<string>(0);
MessageBox("Product is: " + productName);
}
reader.Close();
}
con.Close();
}
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}

Related

How to populate another combobox by selecting value from previous one (cascading)?

I'm having a bit of a problem when trying to populate cascading comboboxes. First part works great, the first combobox gets filled.
Here is the code:
private void LoadCombo()
{
try
{
SqlConnection conn = new SqlConnection(#"Data source=SERVER\SOURCE;Initial Catalog=MyDatabase; Integrated security=true;");
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("select name from sys.tables where type = 'U'", conn);
DataTable dt = new DataTable();
foreach (DataRow row in dt.Rows)
{
comboBox1.Items.Add(row["name"].ToString());
}
}
catch (Exception ex)
{
throw ex;
}
}
Now, all table names are loaded in comboBox1. Now, here's the main problem: I'm trying to retrieve table name from comboBox1 and use the text to pass another query to SQL Server, so that, when I make a selection in comboBox 1, comboBox 2 gets filled with table properties of a specified column of a called table.
Here is the code:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(#"Data source=SERVER\SOURCE;Initial Catalog=MyDatabase; Integrated security=true;");
SqlDataAdapter da = new SqlDataAdapter("select distinct ColumnName from'" + comboBox1.Text + "'", conn);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow row in dt.Rows)
{
comboBox2.Items.Add(row["ColumnName"].ToString());
}
}
catch (Exception ex)
{
throw ex;
}
}
I've been getting an error
Syntax error near columnName
How do I fix this problem? Thank you!

Database is not being updated with Textbox values on button click event

I have an SQL update command for some Textboxes and Comboboxes. However, when the event is fired the database is not getting updated with the Textboxes and I am not getting any exception errors.
The line in particular that I am having an issue with is cmd.Parameters.AddWithValue("#FR_CMMNT", txt_ResolutionNotes.Text);
Here is my code:
private void Button_Click(object sender, RoutedEventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=WINDOWS-B1AT5HC\\SQLEXPRESS;Initial Catalog=CustomerRelations;Integrated Security=True;");
try
{
SqlCommand cmd = new SqlCommand("UPDATE [hb_Disputes] SET FR_DSP_CLSF=#FR_DSP_CLSF, FR_CUST_CNTCT=#FR_CUST_CNTCT, FR_WRK_REQ=#FR_WRK_REQ, FR_OPN_ERR=#FR_OPN_ERR, FR_SO_TP=#FR_SO_TP, FR_SO_DTLS=#FR_SO_DTLS, FR_CMMNT=#FR_CMMNT, FR_SO_DT_WNTD=#FR_SO_DT_WNTD, FINADJ=#FINADJ, SERTYPE=#SERTYPE, CALLRSN=#CALLRSN, SECCAUSE=#SECCAUSE, MTR=#MTR, RPTTYPE=#RPTTYPE, PRMCAUSE=#PRMCAUSE WHERE DSP_ID=#DSP_ID", con);
cmd.Parameters.AddWithValue("#DSP_ID", txt_RowRecrd.Text);
// Second Row
cmd.Parameters.AddWithValue("#FR_DSP_CLSF", cmb_DisputeClassification.SelectedValue);
cmd.Parameters.AddWithValue("#FR_CUST_CNTCT", cmb_CustomerContact.SelectedValue);
cmd.Parameters.AddWithValue("#FR_WRK_REQ", cmb_requestedwork.SelectedValue);
cmd.Parameters.AddWithValue("#FR_OPN_ERR", cmb_OpenInError.SelectedValue);
cmd.Parameters.AddWithValue("#FR_SO_TP", cmb_ServiceOrderType.SelectedValue);
cmd.Parameters.AddWithValue("#FR_SO_DTLS", cmb_ServiceOrderDetails.SelectedValue);
cmd.Parameters.AddWithValue("#FR_CMMNT", txt_ResolutionNotes.Text);
cmd.Parameters.AddWithValue("#FR_SO_DT_WNTD", DatePicker_ScheduledFor.Text);
// Third Row
cmd.Parameters.AddWithValue("#RPTTYPE", cmb_UtilityRptTyp.SelectedValue);
cmd.Parameters.AddWithValue("#FINADJ", cmb_FinancialAdjustment.SelectedValue);
cmd.Parameters.AddWithValue("#SERTYPE", cmb_ServiceTypeAdjustment.SelectedValue);
cmd.Parameters.AddWithValue("#CALLRSN", cmb_InitialCallReason.SelectedValue);
cmd.Parameters.AddWithValue("#PRMCAUSE", cmb_PrimCause.SelectedValue);
cmd.Parameters.AddWithValue("#SECCAUSE", cmb_UnderlyingCause.SelectedValue);
cmd.Parameters.AddWithValue("#MTR", cmb_MeterIssue.SelectedValue);
con.Open();
cmd.ExecuteNonQuery();
cmd.Dispose();
cmd.Dispose();
cmd.Dispose();
MessageBox.Show("Data updated!");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

ADO.net Performing Multiple queries (ExecuteQuery & ExecuteScalar) and displaying the result in a web form control

Hey wish you all to have a happy holiday,
I am trying to display multiple query results from a SQL database table to a grid view control and a label. I have no problem with the grid view result, but the result from the ExecuteScalar command is not displaying inside my lable control with an ID="myCount". I could not figure out what went wrong with my code. I need your help.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MBSDB"].ConnectionString);
try {
conn.Open();
string query="SELECT * FROM tblBook";
using (SqlCommand mycmd = new SqlCommand(query, conn)) {
myGrid.DataSource = mycmd.ExecuteReader();
myGrid.DataBind();
}
string query2 = "SELECT count(title) FROM tblBook";
using (SqlCommand mycmd2 = new SqlCommand(query2, conn)) {
int count = (int)mycmd2.ExecuteScalar();
myCount.Text = count.ToString();
}
}
catch {
Exception(e);
}
finally { conn.Close(); }
}
Are you sure about there is no error. I think, the error occured and handling in the catch block and you are unaware of it.
You should change it;
(int)mycmd2.ExecuteScalar();
to
Convert.ToInt32(mycmd2.ExecuteScalar());
You can't unboxing an object like this; (int)mycmd2.ExecuteScalar()

Get value from list and show to a label

I'm creating a search engine based on SQL database.
Is it possible to get sql data on a List and then show data on labels?
This is my code:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=SHKELQIM\SQLEXPRESS;Initial Catalog=Dictionary;Integrated Security=True");
try
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT Word FROM Dictionary WHERE Word like'%" + lblsearch.Text + "%'", con);
DataSet ds = new DataSet();
da.Fill(ds, "Dictionary");
List<string> word = new List<string>();
foreach (DataRow row in ds.Tables["Dictionary"].Rows)
{
word.Add(row["Word"].ToString());
}
Label1.Text = word[0].ToString();
}
catch (SqlException ex)
{
Label1.Text = ex.Message;
}
finally
{
con.Close();
}
}
}
}
I get an ArgumentOutOfRangeException at line - Label1.Text = word[0].ToString();
I don't know why, because that column contains data.
Also how can I position labels where I want, if I need to create new labels for every word?

The data isn't being loaded into datagrid view. What am i missing?

I think this is one of those times where I'm looking at the code and it all seems fine because my eye's think it will be. I need a fresh set of eyes to look at this code and tell me way it's not loading into the first datagrid view. Thank you for any help your able to provide.
private DataSet DataSetRentals { get; set; }
public DataRelationForm()
{
InitializeComponent();
}
private void DataRelationForm_Load(object sender, EventArgs e)
{
DataSet relationship = new DataSet("relationship");
/////
SqlConnection conn = Database.GetConnection();
SqlDataAdapter adapter = new SqlDataAdapter("Select * From Car", conn);
DataSet DataSetRentals = new DataSet("Relationship");
adapter.FillSchema(DataSetRentals, SchemaType.Source, "Car");
adapter.Fill(DataSetRentals, "Car");
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(DataSetRentals, "Car");
DataTable Car;
Car = DataSetRentals.Tables["Car"];
foreach (DataRow drCurrent in Car.Rows)
{
Console.WriteLine("{0} {1}",
drCurrent["au_fname"].ToString(),
drCurrent["au_lname"].ToString());
}
////////////////////////////////////
SqlDataAdapter adapter2 = new SqlDataAdapter("Select * From CarRental", conn);
adapter.FillSchema(DataSetRentals, SchemaType.Source, "Rentals");
adapter.Fill(DataSetRentals, "Rentals");
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(DataSetRentals, "Rentals");
DataTable CarRental;
CarRental = DataSetRentals.Tables["Rentals"];
foreach (DataRow drCurrent in CarRental.Rows)
{
Console.WriteLine("{0} {1}",
drCurrent["au_fname"].ToString(),
drCurrent["au_lname"].ToString());
}
/////
SqlDataAdapter adapter3 = new SqlDataAdapter("Select * From Customer", conn);
adapter.FillSchema(DataSetRentals, SchemaType.Source, "Customer");
adapter.Fill(DataSetRentals, "Customer");
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(DataSetRentals, "Customer");
DataTable Customer;
Customer = DataSetRentals.Tables["Customer"];
foreach (DataRow drCurrent in Customer.Rows)
{
Console.WriteLine("{0} {1}",
drCurrent["au_fname"].ToString(),
drCurrent["au_lname"].ToString());
}
////////////////////////
DataSetRentals.Tables.Add(Customer);
DataSetRentals.Tables.Add(CarRental);
DataSetRentals.Tables.Add(Car);
DataRelation Step1 = new DataRelation("Customer2CarR",
Customer.Columns["CustomerNo"], CarRental.Columns["CustomerNo"]);
DataSetRentals.Relations.Add(Step1);
DataRelation Step2 = new DataRelation("CarR2Car",
Car.Columns["CarID"], CarRental.Columns["CarID"]);
DataSetRentals.Relations.Add(Step2);
////////////////////////
CustomerGrid.DataSource= DataSetRentals.Tables["Customer"];
CarRGrid.DataSource = DataSetRentals.Tables["CarRental"];
CarGrid.DataSource = DataSetRentals.Tables["Car"];
CustomerGrid.SelectionChanged += new EventHandler(Customer_SelectionChanged);
CarRGrid.SelectionChanged += new EventHandler(CarR_SelectionChanged);
}
private void Customer_SelectionChanged(Object sender, EventArgs e)
{
if (CustomerGrid.SelectedRows.Count > 0)
{
DataRowView selectedRow =
(DataRowView)CustomerGrid.SelectedRows[0].DataBoundItem;
DataSetRentals.Tables["CarRental"].DefaultView.RowFilter =
"CustomerNo = " + selectedRow.Row["CustomerNo"].ToString();
}
else
{
}
}
private void CarR_SelectionChanged(Object sender, EventArgs e)
{
if (CarRGrid.SelectedRows.Count > 0)
{
DataRowView selectedRow =
(DataRowView)CarRGrid.SelectedRows[0].DataBoundItem;
DataSetRentals.Tables["Car"].DefaultView.RowFilter =
"CarID = " + selectedRow.Row["CarID"].ToString();
}
}
And this is the code for the Database.GetConnection() method:
SqlConnectionStringBuilder stringBuilder = new SqlConnectionStringBuilder();
bool OnUni;
OnUni = (System.Environment.UserDomainName == "SOAC") ? true : false;
stringBuilder.DataSource = (OnUni) ? #"SOACSQLSERVER\SHOLESQLBSC" : "(local)";
stringBuilder.InitialCatalog = "CarRental_P117365";
stringBuilder.IntegratedSecurity = true;
return new SqlConnection(stringBuilder.ConnectionString);
It looks like you may have forgotten to call SqlConnection.Open() to actually open the connection. I would also recommend wrapping your connection in a using and explicitly calling SqlConnection.Close() at the end of it, so you don't accidentally leave it open:
using(SqlConnection conn = Database.GetConnection())
{
conn.Open();
/*
rest of code here
*/
conn.Close();
}
For some other good information/examples of properly opening/disposing of SqlConnections, you can also take a look at these SO questions:
Close and Dispose - which to call?
Do I have to Close() a SQLConnection before it gets disposed?
in a "using" block is a SqlConnection closed on return or exception?
youre not binding your data to any datasoruce.
try something like this
using(SqlConnection conn = Database.GetConnection())
try
{
{
------your code here up to DataTable Car-----
DataTable Car;
Car = DataSetRentals.Tables["Car"];
gridview.Datasource = Car;
}
}
catch (SqlException sqlex )
{
string msg = "Fetch Error:";
msg += sqlex.Message;
throw new Exception(msg);
}
Theres no need to open or close the SQL connection as this is done using the using statement at the top where it opens, and when its finishes closes \ disposes of the connection