C# data table loop and find certain columns are not null - c#

I have a datatable with required data.
try
{
using (var connection = conn)
{
using (var command = conn.CreateCommand())
{
command.CommandText = SqlCommand;
command.CommandType = CommandType.Text;
if (connection.State == ConnectionState.Closed)
connection.Open();
command.Connection = connection;
DbDataReader reader = command.ExecuteReader();
var dataTable = new DataTable();
dataTable.Load(reader);
if (dataTable.Rows.Count > 0)
{
}
Datatable has columns from joins.
comments, commnets1, comments2, , ...comments17.
Updateby, Updateby1, updatedby2, ...updatedby17
updateddate,updateddate1, updateddate2, ...updateddate17
So I need to find only the columns tat starts with "abc" and check if they are not null. How can I do this any suggestions ? Thanks for your help. I was thinking if we can create another data table with just those columns and check each column is not empty

Related

Integer is being returned as 0 when it shouldn't be. Retrieved from database

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
}

C# Query MS-Access Table and place read values from column in a text box

Below is a snapshot of my code. I am trying to access the only column in the customer table and place the values into a textbox on the form. I keep getting the error with my code "InvalidOperationException was unhandled" at the line declaring dr as a OleDbDataReader object.
What do I have wrong with the below code that would be giving me this error?
Should I do a list to pick out the text I want from the database?
How can I return the column values from access into a list in C# so that I can search the list for a particular value?
string strsql = "Select * from Customer";
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = strsql;
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
textBox1.Text += dr["Customer"].ToString();
}
conn.Close();
A command carries the info to be executed, a connection carries the info to reach the database server. The two objects should be linked together to produce any result. You miss that line
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = strsql;
cmd.Connection = conn; // <= here
conn.Open();
Remember also that disposable objects like a command, a reader and a connection should be disposed immediately after usage. For this pattern exists the using statement
So you should write
string cmdText = "Select * from Customer";
using(OleDbConnection conn = new OleDbConnection(.....constring...))
using(OleDbCommand cmd = new OleDbCommand(cmdText, conn))
{
conn.Open();
using(OleDbDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
.....
}
}
Here is some sample code.
try
{
using (OleDbConnection myConnection = new OleDbConnection())//make use of the using statement
{
myConnection.ConnectionString = myConnectionString;
myConnection.Open();//Open your connection
OleDbCommand cmdNotReturned = myConnection.CreateCommand();//Create a command
cmdNotReturned.CommandText = "someQuery";
OleDbDataReader readerNotReturned = cmdNotReturned.ExecuteReader(CommandBehavior.CloseConnection);
// close conn after complete
// Load the result into a DataTable
if (readerNotReturned != null) someDataTable.Load(readerNotReturned);
}
}
After that you have a Datatable containing your data. Ofcourse you can afterwards search for records in the Datatable any way you like.

C# How to eliminate duplicate values from comboBox?

I would like to eliminate duplicates from OleDbDataReader
Should be easy but I'm spinning my wheels. Any help would be appreciated!
private void Database_Load(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from PPAPdatabase";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
comboBox_Owner.Items.Add(reader["Owner"].ToString());
}
Refactor your SQL query like this :
select distinct Owner from PPAPdatabase
Instead of
select * from PPAPdatabase
The only column you need in your code is Owner then get that only one column and apply DISTINCT clause to it to get distinct value for that column.
Or replace the following lines :
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
comboBox_Owner.Items.Add(reader["Owner"].ToString());
}
By this :
var owners = dt.AsEnumerable().Select(row => row["Owner"].ToString()).Distinct();
foreach(var owner in owners)
{
comboBox_Owner.Items.Add(owner);
}
In this solution we're using one SQL Query to your Database and reuse the result to extreact distinct owners.
you can do this way
while (reader.Read())
{
if (!comboBox_Owner.Items.Contains(reader["Owner"].ToString()))
comboBox_Owner.Items.Add(reader["Owner"].ToString());
}

Retrieving value from sql ExecuteScalar()

I have the following:
String sql = "SELECT * FROM Temp WHERE Temp.collection = '" + Program.collection + "'";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sql, conn);
Program.defaultCollection = (String)cmd.ExecuteScalar();
And I want to get the second column after executing the statement. I know it will return only one row with two columns
I have read online that I will have to read each row of the result, is there any other way?
ExecuteScalar gets the first column from the first row of the result set. If you need access to more than that you'll need to take a different approach. Like this:
DataTable dt = new DataTable();
SqlDataAdapater sda = new SqlDataAdapter(sql, conn);
sda.Fill(dt);
Program.defaultCollection = dt.Rows[0]["defaultCollection"];
Now, I realize that the field name may not be defaultCollection, but you can fill that in.
From the MSDN documentation for ExecuteScalar:
Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
Now, as a final bit of advice, please wrap all ADO.NET objects in a using statement. Like this:
using (SqlConnection conn = new SqlConnection(connString))
using (SqlDataAdapter sda = new SqlDataAdapter(sql, conn))
{
DataTable dt = new DataTable();
sda.Fill(dt);
// do something with `dt`
}
this will ensure they are properly disposed.
And I want to get the second column after executing the statement
It is not possible with execute scalar.
is there any other way
You have 2 options here either to use SqlDataAdapter or SqlDataReader.
For you using DataReader is a recommended approach as you don't need offline data or do other worh
by using SqlDataAdapter
using (SqlConnection c = new SqlConnection(
youconnectionstring))
{
c.Open();
/
using (SqlDataAdapter a = new SqlDataAdapter(sql, c))
{
DataTable t = new DataTable();
a.Fill(t);
if(t.Rows.Count > 0)
{
string text = t.Rows[0]["yourColumn"].ToString();
}
}
}
by using DataREader
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command =
new SqlCommand(sql, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//read data here
string text = reader.GetString(1)
}
reader.Close();
}
SqlCommand.ExecuteScalar() can be used only when the result have just one row and one column.
If you need more than one column to be returned, you should use something like this:
String sql = "SELECT * FROM Temp WHERE Temp.collection = '" + Program.collection + "'";
SqlConnection conn = new SqlConnection(connString);
using(SqlCommand cmd = new SqlCommand(sql, conn))
{
using(SqlDataReader rdr = cmd.ExecuteReader())
{
if(rdr.Read())
{
Program.defaultCollection = (String)rdr["Column1"];
Program.someOtherVar = (String)rdr["Column2"];
}
}
rdr.Close();
}
That will be the fastest way.
You can use a DataReader and read only the first column like:
IDataReader cReader = cmd.ExecuteReader();
if(cReader.Read())
{
string cText = cReader.GetString(1); // Second Column
}
ExecuteScalar only returns one value. You have to make sure your query only returns that value.
String sql = "SELECT temp.defaultCollection FROM Temp WHERE Temp.collection = '" + Program.collection + "'";
On a side note, read on SqlParameter. You don't want to concatenate values like that, you'll have a problem when the collection property contains a quote.

c# - Do you need a DataTable to retrieve data from a DataAdapter?

Most of my queries are very short, 1-3 records total. This is the code I have now. I am wondering if there is a way to capture userid directly from DataAdapter without going through a table. Thanks!
SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, strCon);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable t = new DataTable();
dataAdapter.Fill(t);
int userid = 0;
if (t.Rows.Count > 0)
{
DataRow dr = t.Rows[0];
userid = dr.Field<int>(0);
If you have only one return value, you can use ExecuteScalar and you have ExecuteReader to get multiple return values.
Here's the msdn sample:
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader[0]));
}
}
}
Use a reader:
http://msdn.microsoft.com/en-US/library/system.data.sqlclient.sqldatareader(v=vs.80).aspx
Quicker and less resources 1 record or hundreds.

Categories