I created win forms, and I wanna insert sql commands and get data from database. If I put query directly into code sql commands, everything is ok, if I put query by textbox I have a lot of bugs like:
$exception {"Could not find stored procedure 'select * from uczniowie'."}
System.Exception {System.Data.SqlClient.SqlException }
this {MateuszLab4.connectDB} MateuszLab4.connectDB
question "\"select * from uczniowie\"" string
dataTable {} System.Data.DataTable
sqlDataReader null System.Data.SqlClient.SqlDataReader
sqlCommand {System.Data.SqlClient.SqlCommand} System.Data.SqlClient.SqlCommand
Here is my code:
private void buttonSearch_Click(object sender, EventArgs e)
{
string query = textBoxQuery.Text;
connectDB databaseWin = new connectDB("(localdb)\\v11.0", "Mat");
dataGridViewAdvanced.DataSource = databaseWin.DataDownload(query);
}
When I put into string query sql commands (for example string query = "select * from students" ) everything is working very well. If I replaced with data from textbox sth is wrong. Could you give me some tips guys?
here is my class with datadownloada:
public DataTable DataDownload(string question)
{
DataTable dataTable = new DataTable();
SqlDataReader sqlDataReader;
SqlCommand sqlCommand;
sqlCommand = new SqlCommand(question);
sqlCommand.Connection = this.DBconnection;
sqlDataReader = sqlCommand.ExecuteReader();
dataTable.Load(sqlDataReader);
return dataTable;
}
Try this code.
public DataTable DataDownload(string question)
{
using (var ada = new SqlDataAdapter(question, DBconnection))
{
// Use DataAdapter to fill DataTable
DataTable dt = new DataTable();
ada.Fill(dt);
return dt;
}
}
Related
I created a Windows Forms application in C# and my database in Visual Studio. I want to know how, if it's possible, to sort one of the columns in the table by clicking a button? Or how can I sort this column automatically without using a button?
I've tried to implement this sort in the code below, but it doesn't work :(
private c void button5_Click(object sender, EventArgs e)
{
SqlConnection sqlConnection = new SqlConnection("Here is my connecting string");
SqlCommand myCommand = new SqlCommand("SELECT * FROM [Information] ORDER BY (Перевозчик)", sqlConnection);
sqlConnection.Open();
myCommand.ExecuteNonQuery();
}
As found here: https://www.w3schools.com/sql/sql_orderby.asp
Sine we don't know what you want to oder we can only guess here.
But with the query you could try:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC
In your case:
"SELECT * FROM [Information] ORDER BY (Перевозчик) ASC"
Best would be to use the visual query builder where you can query against your database. When you are happy with your result you can at least be sure that the query is correct.
How you can do that is explained here:
https://www.c-sharpcorner.com/article/connect-to-a-database-from-visual-studio/
Since the sqlconnection and the sqlcommand is disposable you should consider putting it in a using tag, like in this example.
https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand?view=netframework-4.8
private static void ReadOrderData(string connectionString)
{
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(
queryString, connection);
connection.Open();
using(SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
}
}
There is 2 way for sort data
1) sorting just data and fill into grid:
DataGridView datagridview1 = new DataGridView(); // for show data
DataTable dt1 = new DataTable(); // have data
DataTable dt2 = new DataTable(); // temp data table
DataRow[] dra = dt1.Select("", "ID DESC");
if (dra.Length > 0)
dt2 = dra.CopyToDataTable();
datagridview1.DataSource = dt2;
2) sort default view that is like of sort with grid column header:
DataGridView datagridview1 = new DataGridView(); // for show data
DataTable dt1 = new DataTable(); // have data
dt1.DefaultView.Sort = "ID DESC";
datagridview1.DataSource = dt1;
I found this solution here:
Sorting rows in a data table
For a listbox you could give this a shot
ArrayList q = new ArrayList();
foreach (object o in listBox4.Items)
q.Add(o);
}
q.Sort();
listBox5.Items.Clear();
foreach(object o in q){
listBox5.Items.Add(o);
}
I found this solution here:
Sorting a list of items in a list box
You need to do ExecuteDatareader then process the result coming from this call. ExecuteNonQuery cannot be used to retrieve data.
I have two databases. The first one is shown via a ListBox, and the second one via a ListView. I want to be able to show some information in the ListView based on the chosen ListBox element, but my code doesn't work.
private void DpListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
L.InitReadOnly(false, NameF, LastNameF, AgeF, DepartmentF, ProfessionF, SalaryF);
L.InitReadOnly(false, Name4, LastName4, Age4, Department4, Profession4, Salary4);
int counter = 0;
IEnumerable<Employee> critCareEmp;
critCareEmp = L.EmpUpdate(counter, Emp, DpListBox, Ep);
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter adapter = new SqlDataAdapter();
Console.WriteLine(DpListBox.SelectedValue.ToString());
SqlCommand command = new SqlCommand($#"SELECT * FROM Employee WHERE Dep_nt={DpListBox.SelectedValue}", connection);
adapter.SelectCommand = command;
DataTable dataTable1 = new DataTable();
adapter.Fill(dataTable1);
Ep.ItemsSource = dataTable1.DefaultView;
}
It seems that I need DpListBox.SelectedValue to be some kind of string, but it's not.
SqlCommand command = new SqlCommand
($#"SELECT * FROM Employee WHERE Dep_nt="+
DpListBox.SelectedValue.ToString(),
connection);
please use parameterized stored procedure
inline query is such a bad practice
I have a return value from the stored procedure GetTeam, and I want it to be displayed in the Gridview. This is what I have, but it is not displaying in the gridview:
protected void getTeam()
{
SqlConnection con;
string CS = Configuration.Manager.ConnectionStrings["TEAM"].ConnectionString;
DataTable dt = new DataTable();
using(con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("GetTeam",con);
SqlDataAdapter da = new SqlAdapter(cmd);
da.fill(dt);
Gridview1.Datasource = dt;
Gridview1.Databind();
}
}
Could anyone help?
Here try this solution below, keep in this solution we are sending a parameter to help narrow our results to specific team.
using (SqlConnection conn = new SqlConnection())
{
//Connection string
conn.ConnectionString = ConnectionString.DataSourceString;
//Create adapter and assign store procedure name
SqlCommand cmmd = new SqlCommand()
{
CommandType = CommandType.StoredProcedure
};
// Assign to Command type
//exception is caught because it cannot find Stored Procedure
//Insert parameters into row from input text
cmmd.CommandText = "GetTeam";
// Send parameter
cmmd.Parameters.AddWithValue("#PGetDayTeam",
ShiftParameterTextBox.Text.Trim());
cmmd.Connection = conn;
try
{
conn.Open();
//If we do not receive any records
GridView2.EmptyDataText = "No Records Found";
GridView2.DataSource = cmmd.ExecuteReader();
GridView2.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
// Close and dispose connection
conn.Close();
conn.Dispose();
}
// select from grid
protected void GridView2_SelectedIndexChanging(Object sender, GridViewSelectEventArgs e)
{
GridViewRow row = GridView2.Rows[e.NewSelectedIndex];
string GetTeam = row.Cells[2].Text;
// You can use it in viewstate or what you choose.
ViewState["GetTeam"] = GetTeam;
}
The Fill operation then adds the rows to destination DataTable objects
in the DataSet, creating the DataTable objects if they do not already
exist. When creating DataTable objects, the Fill operation normally
creates only column name metadata. However, if the MissingSchemaAction
property is set to AddWithKey, appropriate primary keys and
constraints are also created.
You're using sql prosedure. So you already have a Colums' name. You don't need to use DataTable. The Sql adapter can fill dataset also. You need to use DataSet first.
public static DataSet ExecuteDataset(SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
//create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters);
//create the DataAdapter & DataSet
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
//fill the DataSet using default values for DataTable names, etc.
da.Fill(ds);
//return the dataset
return ds;
}
Then you can bind your Gridview with that one.
grdView.DataSource = ds;
grdView.DataBind();
I have a DbConnect class which queries a MySQL database and store the results into a datatable - something like this:
public DataTable selectCombo()
{
string query = "SELECT DISTINCT month FROM printer_count";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
}
this.CloseConnection();
return dt;
}
Now how to retrieve the datatable from the class into the combo box main form? Can I do something like this?
ComboBox1.DataSource = dbConnect();
ComboBox1.DisplayMember = "Name"; // column name to display
You have two variables with the same name. (dt) One is defined as a string, the other one inside the if block is defined as a datatable. You return the empty string and this, of course, cannot work when you try to assign the DataSource of the combo
public DataTable selectCombo()
{
DataTable dt = new DataTable();
string query = "SELECT DISTINCT month FROM printer_count";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
}
this.CloseConnection();
return dt;
}
Now you could write
....
ComboBox1.DisplayMember = "Name";
ComboBox1.DataSource = selectCombo();
.....
Also this code is not very safe. If, for any reason, you get an exception, the CloseConnection will not be called leaving an open connection around and this is very problematic for the stability of your system. However, fixing that problem, requires a different approach to you OpenConnection code. Instead of true this method should return the MySqlConnection object so your calling code could apply the using statement around the connection instance
I have programmatically created a chart using ASP.Net, now I just need to figure out how to connect to an oracle sql developer database and retrieve the data to populate the chart.
Would I use an OleDb method (see below), along with some other logic?
using System.Data.OleDb;
OleDbConnection myConnection = new OleDbConnection;();
myConnection.ConnectionString = myConnectionString;
myConnection.Open();
//execute queries, etc
myConnection.Close();
Any help would be great.
http://justins-fat-tire.blogspot.com/
I've got some code examples that show how to use a stored procedure to fill a dataset/table and get a generic List of object data. If you're using raw sql you will need to modify the command object a bit.
You would use a DataTable as the data source for the chart. To do this, you first need to populate the table.
public void Populate()
{
Datatable data = GetData();
foreach(DataRow r in data.Rows)
{
/// Populate chart using data
}
}
public DataTable GetData()
{
try
{
OleDbConnection myConnection = new OleDbConnection;();
myConnection.ConnectionString = myConnectionString;
myConnection.Open();
OleDbCommand myCommand = myConnection.CreateCommand();
//Set commandtype and text here.
myCommand.CommandType = SOMETYPE;
myCommand.CommandText = "SOMETEXT";
OleDbDataReader reader = myCommand.ExecuteReader();
DataTable t = new DataTable();
t.Load(reader);
return t;
}
catch (Exception e)
{
throw e;
}
finally
{
myConnection.Close();
}
}