Dataset filter method - c#

Here is my code,
Conn.Open();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
SqlCommand sqlCmd = new SqlCommand("SELECT * from CurrentDataCR ",Conn);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(ds);
ds.Tables[0].DefaultView.RowFilter = " mst_remote_station_id Like'*9001*'";
Here I am getting Complete row for id 9001. I need only one column value for this id.

DataRow[] rows = ds.Tables[0].Select("mst_remote_station_id Like '%9001%'");
You can do it this way also if you need only one row just select it in the initial query.
Also you should Dispose the SqlDataAdapter after using it ! You can do it with using block
Conn.Open();
DataSet ds = new DataSet();
SqlCommand sqlCmd = new SqlCommand("SELECT * from CurrentDataCR ",Conn);
using(SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(ds);
}
ds.Tables[0].Select("mst_remote_station_id Like '%9001%'");
I don't know if the connection is global but it is bad practice to use global connection, you have connection pool so use separate connection for every query.

Related

Read data from a database in C#

I have created a table name glossary in a database named ChatBotDataBase in SQL Server. I want to read the data in a special column of the table.
To do so, I have written this code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection sc = new SqlConnection();
sc.ConnectionString = #"Data Source=shirin;Initial Catalog=ChatBotDataBase;
Integrated Security=True";
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = new SqlCommand();
sda.SelectCommand.Connection = sc;
sda.SelectCommand.CommandText = "SELECT * FROM glossary";
DataTable table = new DataTable();
MessageBox.Show(table.Rows[0].ItemArray[3].ToString());
}
But there is an error in last line.
The error is :
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll.
And here is a print screen of the mentioned table:
Can anyone help please?
Looks like you are confusing the Datatable called table with your database table in your sql server. In your image you show us the glossary table in your sql server, not the DataTable called table.
You get this error because you create an empty DataTable called table with DataTable table = new DataTable() but you didn't even fill your table. That's why it doesn't have any rows by default.
SqlCommand cmd = new SqlCommand("SELECT * FROM glossary");
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(table);
Also use using statement to dispose your SqlConnection, SqlCommand and SqlDataAdapter.
using(SqlConnection sc = new SqlConnection(conString))
using(SqlCommand cmd = sc.CreateCommand())
{
cmd.CommandText = "SELECT * FROM glossary";
...
using(SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable table = new DataTable();
sda.Fill(table);
if(dt.Rows.Count > 0)
MessageBox.Show(table.Rows[0].ItemArray[3].ToString());
}
}
Below code will help you
sda.SelectCommand.CommandText = "SELECT * FROM glossary";
DataTable table = new DataTable();
sda.Fill(table , "glossary");
MessageBox.Show(table.Rows[0].ItemArray[3].ToString());
You haven't executed the query or populated the table. It is empty. It has no columns and no rows. Hence the error.
Frankly, though, I strongly suggest using a typed class model, not any kind of DataTable. With tools like "dapper", this can be as simple as:
var list = conn.Query<Glossary>("SELECT * FROM glossary").ToList();
With
public class Glossary {
public int Id {get;set}
public string String1 {get;set} // horrible name!
....
public int NumberOfUse {get;set}
}
Dear kindly first fill your table with the data.
And you should use checks because if there is no data then you get a proper message.check is below..
if(dt.Rows.Count > 0)
MessageBox.Show(table.Rows[0].ItemArray[3].ToString());
else if(dt.Rows.Count > 0)
MessageBox.Show("Table is empty");
And other advice is that you should display data into DataGrid.... Displaying data from Database into a message box is not a good programming approach..
For displaying DataTable into DataGrid in C# is as simple as below.
SqlCommand cmd = new SqlCommand("select * from student",con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
dt.TableName = "students";
da.Fill(dt);
dataGridView1.DataSource =dt;
using System.Data.Odbc;
OdbcConnection con = new OdbcConnection("<connectionstring>");
OdbcCommand com = new OdbcCommand("select * from TableX",con);
OdbcDataAdapter da = new OdbcDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds,"New");
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables["New"];
you can get the connection string from:
http://www.connectionstrings.com/

SQL Server Views with asp.net

I have created a view called view_SelectAll_Student in SQL Server which retrieves all columns from single table name
And I have a function that returns dataset or datatable using dataadapter somehow I get this error:
The request for procedure 'view_SellectAll_Student' failed because 'view_SellectAll_Student' is a view object.
Code:
public DataTable ViewStudentAll()
{
cons.Open();
DataTable dt = new DataTable();
cmd = new SqlCommand("view_SellectAll_Student", cons);
cmd.Connection = cons;
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
cmd.Dispose();
cons.Close();
adp.Dispose();
return dt;
}
Views still need to be queried. What you have here is just the view name..
So change this:
cmd = new SqlCommand("view_SellectAll_Student",cons);
to this:
cmd = new SqlCommand("SELECT put, columns, here FROM view_SellectAll_Student",cons);
Make sure you put the columns of the view there (or an asterisk.. if you're that way inclined).
Write it like this. If its a view you should SELECT it otherwise you wont get it.
cmd = new SqlCommand("SELECT * FROM view_SellectAll_Student",cons);
cmd.Connection = cons;
//cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
cmd.Dispose();
cons.Close();
adp.Dispose();
return dt;
TIP: While using a DataAdapter there is no need of con.Open() or con.Close() statement. DataAdapter itself will open and close it.
The SqlDataAdapter accepts as first argument an SqlCommand which can
be a Select statement or stored procedure.
In this case you can replace "view_SellectAll_Student" with
"Select * from view_SellectAll_Student"
cons.Open();
DataTable dt = new DataTable();
cmd = new SqlCommand("select * view_SellectAll_Student",cons);
cmd.Connection = cons;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
cmd.Dispose();
cons.Close();
adp.Dispose();
return dt;

Want to show data from two different tables in two different datagridviews in a form in c#

I have two different queries for two different tables I want to show the result in two datagridviews on a form
string query1 = string.Format("select * from Flat where [Flat_No.]='{0}'",flat.Text);
string query2 = string.Format("select * from 1");
SqlCommand cmd = new SqlCommand(query1, con);
SqlCommand cmd1 = new SqlCommand(query2, con1);
dataview frm1 = new dataview(query1,query2); //the form where data is to be displayed
// on form dataview I have two DataGridViews
public dataview(string a,string b)
{
InitializeComponent();
SqlConnection con = new SqlConnection(Class1.getConnectionString);
//connection name
con.Open();
SqlCommand cmd = new SqlCommand(a , con);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "ss");
dataGridView1.DataSource = ds.Tables["ss"];
con.Close();
SqlConnection con1 = new SqlConnection(Class1.getConnectionString);
//connection name for query1
con1.Open();
SqlCommand cmd1 = new SqlCommand(b, con1);
cmd1.CommandType = CommandType.Text;
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
DataSet ds1 = new DataSet();
da.Fill(ds1, "aa");
dataGridView2.DataSource = ds1.Tables["aa"];
con1.Close();
}
}
but the above code is showing data from query 1 in both the datagridviews. plz help me out how can I solve this problem? If there in another way let me know it also. I have also tried to merge both the queries using "+" sign but it also didn't proved helpful.
Use da1.Fill instead of da.fill. You're using the da DataAdapter for filling both Datasets
da.Fill(ds1, "aa");
da1.Fill(ds1, "aa");

How use WHERE in SqlDataAdapter in C#

How use WHERE in SqlDataAdapter in C#?
I want get name in a textbox and use that at query but it wont work .
SqlConnection sqlconnection = new SqlConnection("Server=Behnam\\Accounting;Initial Catalog=Accounting;Integrated Security=TRUE");
DataTable dt = new DataTable();
string _search_name = txt_search.Text;
SqlDataAdapter SDA = new SqlDataAdapter("SELECT dbo.tbl_user.field1,dbo.tbl_user.field2 FROM tbl_user WHERE dbo.tbl_user.name=_search_name ", sqlconnection);
SDA.Fill(dt);
dataGridView1.DataSource = dt;
Prepare the command text and use a parameter for the value of your search.
Then use that command text to initialize a new SqlCommand. Fill the parameter value with AddWithValue and pass the SqlCommand to the constructor of the SqlDataAdapter.
string cmdText = "SELECT dbo.tbl_user.field1,dbo.tbl_user.field2 " +
"FROM tbl_user WHERE dbo.tbl_user.name=#search_name"
SqlCommand cmd = new SqlCommand(cmdText, sqlconnection);
cmd.Parameters.AddWithValue("#search_name", _search_name);
SqlDataAdapter SDA = new SqlDataAdapter(cmd);
The SqlDataAdapter will store your command as the SelectCommand property and will use the passed in SqlCommand to execute the query to retrieve the records from the database.
Keep in mind that AddWithValue is a shortcut with some drawbacks. For example it pass Always a string as a nvarchar parameter with size equal to the actual lenght of the variable. This effectively reduces the performance of the Sql Server Optimizer.
This is a very enlightening article on the issue
So, you were pretty close, you just needed to define a parameter inside the query and then add that parameter. However, in the following code block I've also conveniently recommended a more appropriate approach to using the classes needed to get the data (pun intended). The using statement here ensures that the objects get disposed of properly after you are done using them (man I just can't stop with the puns!)
using (SqlConnection c = new SqlConnection(connString))
{
c.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(
"SELECT dbo.tbl_user.field1, dbo.tbl_user.field2 FROM tbl_user " +
"WHERE dbo.tbl_user.name= #name", c))
{
sda.SelectCommand.Parameters.AddWithValue("#name", txt_search.Text);
DataTable dt = new DataTable();
sda.Fill(dt);
}
}
Try this.
you were using the string directly in the query which will go undetected.
SqlConnection sqlconnection = new SqlConnection("Server=Behnam\\Accounting;
Initial Catalog=Accounting;Integrated Security=TRUE");
DataTable dt = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter("SELECT dbo.tbl_user.field1,dbo.tbl_user.field2 FROM tbl_user WHERE dbo.tbl_user.name=#searchName" , sqlconnection);
SDA.SelectCommand.Parameters.AddWithValue("#searchName", txt_search.Text);
SDA.Fill(dt);
dataGridView1.DataSource = dt;

Prepared SELECT statement in .Net

I can't understand what I am doing wrong, I can't seem to SELECT with a prepared statement. However I can INSERT with a prepared statement.
MySqlCommand cmd = new MySqlCommand("SELECT * FROM code_post WHERE name = ?postRequired LIMIT 1", dbcon);
cmd.Parameters.Add(new MySqlParameter("?postRequired", requestString));
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
cmd.fill(ds, "result");
try {
thisBlog = ds.Tables["result"].Rows[0];
} catch {
invalid();
return;
}
Any advice on this would be greatly appreciated!
To fill a DataSet you will need a DataAdapter.
Try this:
MySqlCommand cmd = new MySqlCommand("SELECT * FROM code_post WHERE name = ?postRequired LIMIT 1", dbcon);
cmd.Parameters.Add(new MySqlParameter("?postRequired", requestString));
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
MySqlDataAdapter dAdap = new MySqlDataAdapter();
dAdap.SelectCommand = cmd;
dAdap.Fill(ds, "result");
try {
thisBlog = ds.Tables["result"].Rows[0];
} catch {
invalid();
return;
}
You need to use SqlDataAdapter
DataAdapter represents a set of data commands and a database connection that are used to fill the DataSet and update a SQL Server database.
The SqlDataAdapter provides this bridge by mapping Fill, which changes the data in the DataSet to match the data in the data source
Check the following syntax:
private static DataSet SelectRows(DataSet dataset,
string connectionString,string queryString)
{
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(
queryString, connection);
adapter.Fill(dataset);
return dataset;
}
}

Categories

Resources