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

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!

Related

Passing DropDownList value into SQL command in ASP.net

I have a DropDownList which gets it values from SQL table
I want to get the Average of the selected item (course in this case) from the dropDownList and to show it in a label :
This section works -
SqlConnection sqlConnection1;
sqlConnection1 = new SqlConnection(#"Data Source=HA\SQLEXPRESS; Initial Catalog=Grades1; Integrated Security=True");
SqlCommand Command = null;
Command = new SqlCommand("SELECT Course FROM GradesTable1", sqlConnection1);
Command.Connection.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter(Command);
DataTable dataTble1 = new DataTable();
dataAdapter.Fill(dataTble1);
if (dataTble1.Rows.Count > 0)
{
foreach (DataRow row in dataTble1.Rows)
{
ListItem course1 = new ListItem(row["Course"].ToString());
if (!DropDownList1.Items.Contains(course1))
{
DropDownList1.Items.Add(course1); // showing the 2 courses
}
}
}
Command.Connection.Close();
}
}
Here is the problem - (I get nothing, no data )
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection sqlConnection1;
sqlConnection1 = new SqlConnection(#"Data Source=HA\SQLEXPRESS; Initial Catalog=Grades1; Integrated Security=True");
SqlCommand Command = null;
Command = new SqlCommand($"SELECT AVG(Grade) FROM GradesTable1 WHERE Course = #course", sqlConnection1);
Command.Parameters.AddWithValue("#course", DropDownList1.SelectedItem);
Command.Connection.Open();
SqlDataReader sqlDataReader1 = Command.ExecuteReader();
if (sqlDataReader1.Read())
{
LabelAverage.Text = sqlDataReader1[0].ToString();
}
else
{
LabelAverage.Text = "No Data"; // doesn't get into here anyhow
}
}
EDIT
I tried several variations as $"SELECT AVG(Grade) AS "ClassAVG" FROM GradesTable1 WHERE Course = #course" and Command.Parameters.AddWithValue("#course", DropDownList1.SelectedItem.Text), or DropDownList1.SelectedValue
I believe the problem is with the DropDownlist values which being received from the SQL and are not hard coded.
Is there a correct way to this? is it possible without knowing what are the "Courses" in advanced?
Thanks for the answers, feel free to give your opinion.
I found out what was missing in the DropDownList in aspx page (not the aspx.cs page) -the AutoPostBack="true"
Adding that to DropDownList solved the problem.
// query = Sql query
query.Select(s => new MusteriNoktaComboItemDTO
{
Label = s.Adi,
Value = s.ID.ToString()
}).ToList();

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

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?

How do I print SQL query using MessageBox in C#

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

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