I'm trying to populate a checkedlistbox from a list
my approach:
SqlCommand getlocationnames = new SqlCommand("allLocationNames", conn);
getlocationnames.CommandType = CommandType.StoredProcedure;
conn.Open();
SqlDataReader dr = getlocationnames.ExecuteReader();
List<locations> results = new List<locations>();
while (dr.Read())
{
locations newItem = new locations();
newItem.loc_name = dr.GetString(0);
results.Add(newItem);
}
dr.Close();
foreach (var result in results)
{
checkedListBox1.Items.Add(result);
}
Does some one see what I'm missing here?
Try this approach (instead of two loops, one loop is used in this approach, which increases the application's speed):
Output:
SQL (a StoredProcedure which is already created in the database):
Create Procedure AllValues As Select * From YourTableName
Go
C#:
System.Data.SqlClient.SqlConnection Connection = new System.Data.SqlClient.SqlConnection("Data Source =.;" + "AttachDbFilename = " + Application.StartupPath + #"\YourDataBaseName.mdf;" + "Integrated Security = True;");
private void AddButton_Click(object sender, EventArgs e)
{
Connection.Open();
System.Data.SqlClient.SqlCommand Command = new System.Data.SqlClient.SqlCommand();
Command.Connection = Connection;
Command.CommandType = CommandType.StoredProcedure;
Command.CommandText = "AllValues";
System.Data.SqlClient.SqlDataReader DataReader = Command.ExecuteReader();
List<object> results = new List<object>();
//DataReader[0] means the first column of the table
//DataReader[1] means the second column of the table
while (DataReader.Read())
{
results.Add(string.Join(null, "Country = ", DataReader[0].ToString(), "\t\t", "Capital = ", DataReader[1].ToString()));
}
Connection.Close();
checkedListBox.Items.Clear();
checkedListBox.Items.AddRange(results.ToArray());
}
private void ClearButton_Click(object sender, EventArgs e)
{
checkedListBox.Items.Clear();
}
Tested in:
Visual Studio 2017, .NET Framework 4.5.2, Windows Forms, SQL Server 12.0.6024.0
Related
I am new to C# and I have connected it with Oracle11g and using Visual Studio 2013 as a tool. I am trying to display a 'name ' that is being returned by a query to a textbox but it is neither displaying an Error Message nor displaying the Output. Pleases help me to resolve this problem. Thanks... here is my code..
private void button1_Click(object sender, EventArgs e)
{
try
{
string oradb = "Data Source=ORCL;User Id=hr; Password=123;";
OracleConnection conn = new OracleConnection(oradb); // C#
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select name from std where cgpa=2.82;";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
textBox1.Text = dr.GetString(0);
conn.Dispose();
}
catch (Exception ex) { MessageBox.Show("\n"+ex); }
}
after setting textBox1.Text = dr.GetString(0);
it is giving me the attached exception.
Array indexes start at index zero, not 1. The returned string (if any) is at
textBox1.Text = dr.GetString(0);
A more correct way to write your code is the following
private void button1_Click(object sender, EventArgs e)
{
try
{
string oradb = "Data Source=ORCL;User Id=hr; Password=123;";
// Use the using statements around disposable objects....
using(OracleConnection conn = new OracleConnection(oradb))
using(OracleCommand cmd = new OracleCommand())
{
conn.Open();
// These two parameters could be passed directly in the
// OracleCommand constructor....
cmd.Connection = conn;
cmd.CommandText = "select name from std where cgpa=2.82;";
// Again using statement around disposable objects
using(OracleDataReader dr = cmd.ExecuteReader())
{
// Check if you have a record or not
if(dr.Read())
textBox1.Text = dr.GetString(0);
}
}
}
catch (Exception ex) { MessageBox.Show("\n"+ex); }
}
And if your code is supposed to return just a single record with a single column then you can use the more performant ExecuteScalar without building an OracleDataReader
// Again using statement around disposable objects
object result = cmd.ExecuteScalar();
if(result != null)
textBox1.Text = result.ToString();
I have some data stored in a SQLite database which I want to display on a webpage in C#. I searched for the right thing to do but only found console.writeline, and beside that the SqliteDataReader function is not working. This is my code:
protected void Page_Load(object sender, EventArgs e)
{
using (System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection("Data Source=C:/Users/elias/Documents/Visual Studio 2017/WebSites/WebSite7/App_Data/overhoren.db"))
{
using (System.Data.SQLite.SQLiteCommand command = new System.Data.SQLite.SQLiteCommand(conn))
{
conn.Open();
command.Connection = conn;
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
string test = ("Name: " + reader["name"] + "\tScore: " + reader["score"]);
command.ExecuteNonQuery();
conn.Close();
}
}
What should I do?
Thanks in advance,
Elias
It seems that you've forgot to put the actual query to perform:
command.CommandText = "...";
Something like this:
protected void Page_Load(object sender, EventArgs e)
{
//TODO: do not hardcode connection string, move it to settings
string connectionString =
#"Data Source=C:/Users/elias/Documents/Visual Studio 2017/WebSites/WebSite7/App_Data/overhoren.db";
// var for simplicity
using (var conn = new System.Data.SQLite.SQLiteConnection(connectionString))
{
conn.Open();
using (var command = new System.Data.SQLite.SQLiteCommand(conn))
{
command.Connection = conn;
//TODO: put the right SQL to perform here
command.CommandText =
#"select name,
score
from MyTable";
using (var reader = command.ExecuteReader()) {
string test = "";
// do we have any data to read?
//DONE: try not building string but using formatting (or string interpolation)
if (reader.Read())
test = $"Name: {reader["name"]}\tScore: {reader["score"]}";
//TODO: so you've got "test" string; do what you want with it
}
}
//DONE: you don't want command.ExecuteNonQuery(), but command.ExecuteReader()
//DONE: you don't want conn.Close() - "using" will do it for you
}
}
Hi I'm new to C# and I have a windows form with a textbox Barcode_txtBx and a button Search_btn which filters records in a Data Table dt to one record and have another textbox Manufacturer_txtBx to display the data table column Manufacturer. I can do the filtering but I can't find a way to display the relevant column in the textbox Manufacturer_txtBx. This is the code I have so far.
private void Search_btn_Click(object sender, EventArgs e)
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "Select * from BookInTable where Barcode = '" + Barcode_txtBx.Text + "'";
OleDbDataReader reader = command.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
Manufacturer_txtBx.Text = "";
connection.Close();
}
At the moment Manufacturer_txtBx is displaying an empty string just so I don't get an error
This works to add the data to the TextBoxes
private void Search_btn_Click(object sender, EventArgs e)
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "Select * from BookInTable where Barcode = '" + Barcode_txtBx.Text + "'";
OleDbDataReader reader = command.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
string data = dt.ToString();
Manufacturer_txtBx.Text = dt.Rows[0].ItemArray[5].ToString();
Type_txtBx.Text = dt.Rows[0].ItemArray[6].ToString();
Model_txtBx.Text = dt.Rows[0].ItemArray[7].ToString();
PartNumber_txtBx.Text = dt.Rows[0].ItemArray[8].ToString();
AdditionalDetails_txtBx.Text = dt.Rows[0].ItemArray[13].ToString();
connection.Close();
}
Crowcoder and Steve are right that this is not sanitised in any way and any working database should be.
I'm trying to get a value from my database but it keeps returning a value of 0 and i cannot figure out why. I've been retrieving data from the database for the whole of my project and it is just not working here. None of the values in the database are = to 0.
int rentalPrice is the one being returned as 0`
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["id"] == null)
{
Response.Redirect("DisplayCars.aspx");
}
else
{
id = Convert.ToInt32(Request.QueryString["id"].ToString());
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from cars where id ='" + id + "'";
cmd.ExecuteNonQuery();
lblCarID.Text = id.ToString();
DataTable dt2 = new DataTable();
SqlDataAdapter da2 = new SqlDataAdapter(cmd);
foreach (DataRow dr2 in dt2.Rows)
{
rentalPrice = Convert.ToInt32(dr2["car_rental_price"]);
}
lblRentalPrice.Text = rentalPrice.ToString();
con.Close();
}
// This uses a Connection pool, so you don't need to reuse the same SqlConnection
using (SqlConnection con = new SqlConnection(...))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select [car_rental_price] from cars where id = #Id";
var idParam = new SqlParameter("#Id");
idParam.Value = id;
cmd.Parameters.Add(idParam);
con.Open();
using (var reader = cmd.ExcecuteReader())
{
reader.Read();
lblRentalPrice.Text = reader.GetInt32(0).ToString();
lblCarID.Text = id.ToString();}
}
}
}
To execute a query and get results, you need to use cmd.ExecuteReader.
Also, rather than concatenating values into a string to build your SQL query, you need to use parameterized queries. This helps prevent SQL Injection attacks.
Also, SqlConnection should not be put in a field (class level variable). Instead, you should use local variables and wrap them in a using statement to ensure that they get disposed of properly.
hey you did not fill the Data Table.. then how it has any Values???
first Fill the data Table and use it in Foreach loop
adapter.Fill(DataTable);
foreach(DataRow dr in DataTable)
{
//get the id
}
I ran the SQL Query in SQL Server Management Studio and it worked.
I get the following error in my WinForm C# application
The parameterized query '(#word1 text)SELECT distinct [database].[dbo].[tableName].[n' expects the parameter '#word1', which was not supplied.
Here is my code
private void buttonRunQuery_Click(object sender, EventArgs e)
{
if (connection == null)
{
connection = ConnectionStateToSQLServer();
SqlCommand command = new SqlCommand(null, connection);
command = createSQLQuery(command);
GetData(command);
}
else
{
SqlCommand command = new SqlCommand(null, connection);
command = createSQLQuery(command);
GetData(command);
}
}
private SqlCommand createSQLQuery(SqlCommand command)
{
string[] allTheseWords;
if (textBoxAllTheseWords.Text.Length > 0)
{
allTheseWords = textBoxAllTheseWords.Text.Split(' ');
string SQLQuery = "SELECT distinct [database].[dbo].[customerTable].[name], [database].[dbo].[customerTable].[dos], [database].[dbo].[customerTable].[accountID], [database].[dbo].[reportTable].[customerID], [database].[dbo].[reportTable].[accountID], [database].[dbo].[reportTable].[fullreport] FROM [database].[dbo].[reportTable], [database].[dbo].[customerTable] WHERE ";
int i = 1;
foreach (string word in allTheseWords)
{
var name = "#word" + (i++).ToString();
command.Parameters.Add(name, SqlDbType.Text);
//(name, SqlDbType.Text).Value = word;
SQLQuery = SQLQuery + String.Format(" [database].[dbo].[reportTable].[fullreport] LIKE {0} AND ", name);
}
SQLQuery = SQLQuery + " [database].[dbo].[customerTable].[accountID] = [database].[dbo].[reportTable].[accountID]";
command.CommandText = SQLQuery;
}
MessageBox.Show(command.CommandText.ToString());
return command;
}
public DataTable GetData(SqlCommand cmd)
{
//SqlConnection con = new SqlConnection(connString);
//SqlCommand cmd = new SqlCommand(sqlcmdString, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
connection.Open();
DataTable dt = new DataTable();
da.Fill(dt);
connection.Close();
return dt;
}
The error is happening on da.Fill(dt)
Any suggestions would be helpful
Thank you
In your example, you have commented out the line where you set the value of the Parameter:
command.Parameters.Add(name, SqlDbType.Text);
//(name, SqlDbType.Text).Value = word;
If you do not set a value for a parameter, it is ignored (and won't exist).
Change to this:
command.Parameters.AddWithValue(name, word);
For clarity, consider this quote:
The value to be added. Use DBNull.Value instead of null, to indicate a null value.
From here: SqlParameterCollection.AddWithValue Method
On var name = "#word" + (i++).ToString(); use just i, increment somewhere else.