datagrid not getting displayed - c#

I am trying to display the data from sql into a datagrid as follows:
try
{
SqlConnection xconn = new SqlConnection();
xconn.ConnectionString = #"Data Source=servername; Trusted_Connection=yes; Database=master";
xconn.Open();
string s = "select * from tablename where name=#name";
SqlCommand ycmd = new SqlCommand(s, xconn);
ycmd.Parameters.Add("#name", dropdownlistname.SelectedValue);
SqlDataAdapter da = new SqlDataAdapter(ycmd);
DataTable dt = new DataTable();
da.Fill(dt);
gridview.DataSource = dt;
gridview.DataBind();
}
catch (Exception e2)
{
lblresult.Text = e2.Message + "<br />" + e2.StackTrace ;
}
I do not get any exception . However , the grid is not displayed.

try like this....
you can change this depends on your requirement ....
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT * FROM Product WHERE Product.ID=#PROD_ID";
command.Parameters.Add(new SqlParameter("#PROD_ID", 100));
// Execute the SQL Server command...
SqlDataReader reader = command.ExecuteReader();
DataTable tblProducts = new DataTable();
tblProducts.Load(reader);
foreach (DataRow rowProduct in tblProducts.Rows)
{
// Use the data...
}

It doesn't work because you are defining a parameter #name to your sql statement but you are never feeding any value since the version of SqlCommand.Parameters.Add that takes 2 parameters is the one that receives parameterName and SqlDbType
I am surprised you are not getting exceptions. Perhaps your dropdownlistname.SelectedValue matches one of the enumeration values for SqlDbType and that's why?
You should be doing:
ycmd.Parameters.AddWithValue("#name", dropdownlistname.SelectedValue);

Related

How to display the proper data?

I have 2 datagridviews now i want to select a column named "Name" in the first datagridview and us it as the WHERE in my query to Select values from a table and put it in the other datagridview.
SqlCommand cmd = new SqlCommand();
cmd = ss.CreateCommand();
foreach (DataGridViewRow row in dgvAtt.Rows)
{
ss.Open();
cmd.CommandType = CommandType.Text;
string Query = "SELECT Signature FROM TBL_Student WHERE Name = '" +
row.Cells[4].Value.ToString() + "' ";
cmd.CommandText = Query;
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter dp = new SqlDataAdapter(cmd);
dp.Fill(dt);
dgvSign.DataSource = dt;
ss.Close();
}
but it gives me error when there is null and it is only selecting the first row in the first datagridview.
You create in each foreach-loop a new DataTable and therefore it will always just have one Value. So you have to create it before the foreach-loop.
And make sure you check the Values you want to use before using them.
With this easy if-condition, there won't be any problems.
Edit1:
This code snippet is working just fine.
Just change the ConnectionString and you are done.
DataTable dt = new DataTable();
string error;
using (SqlConnection con = new SqlConnection(#"Data Source=SERVER;Initial Catalog=DATEBASE; User ID=USERNAME; Password=PASSWORD"))
{
SqlCommand cmd = new SqlCommand();
foreach (DataGridViewRow row in dgvAtt.Rows)
{
string Query = "SELECT Signature FROM TBL_Student WHERE Name = '";
if (row.Cells.Count >= 4 && row.Cells[4].Value != null)
{
Query += row.Cells[4].Value.ToString();
}
Query += "'";
try
{
cmd = new SqlCommand(Query, con);
if (con.State == ConnectionState.Closed)
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
}
catch (Exception ex)
{
error = ex.Message;
}
}
}
dgvSign.DataSource = dt;

C# & SQL Server : searching all database columns and populating datagrid

I am writing a a C# application, and I am stuck at searching the database and populating a data grid view. However I want to use this with command builder.
The issue is, I need the search to work across all columns in the database. I thought using OR and LIKE statements would do this. But instead I get either invalid syntax or no column name exists in the search.
Does anyone know a solution?
My current .cs:
private void btnSearchJob_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = (#"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=MTR_Database;Integrated Security=True");
string selectQuery = "SELECT * FROM dbo.[" + cmbJobName.Text + "] WHERE ([Job Name] LIKE " +txtSearchJob.Text+ " OR [Manufacturer] LIKE " +txtSearchJob.Text+ ")";
// DataAdapter
myDA = new SqlDataAdapter(selectQuery, con);
// SqlCommand
SqlCommand myCMD = new SqlCommand(selectQuery, con);
// DataAdapter to Command
myDA.SelectCommand = myCMD;
// Define Datatable
myDT = new DataTable();
// Command Builder (IS GOD!)
SqlCommandBuilder cb = new SqlCommandBuilder(myDA);
// Teach Command builder to be a boss!
myDA.UpdateCommand = cb.GetUpdateCommand();
myDA.InsertCommand = cb.GetInsertCommand();
myDA.DeleteCommand = cb.GetDeleteCommand();
// Fill the DataTable with DataAdapter information
myDA.Fill(myDT);
// Fill DataTable with Database Schema
myDA.FillSchema(myDT, SchemaType.Source);
// Bind The Data Table to the DataGrid
dataGridView1.DataSource = myDT;
// AutoSize Datagrid Rows and Colums to fit the Datagrid
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
}
// Catch Exception
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "SQL ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
NOTE:
I am aware of using parameters, I am simply using this to see if it will work when I will add parameters later.
this is what I use to get everything back into a DataTable
//'places the call to the system and returns the data as a datatable
public DataTable GetDataAsDatatable(List<SqlParameter> sqlParameters, string connStr, string storedProcName)
{
var dt = new DataTable();
var sqlCmd = new SqlCommand();
using (var sqlconn = new SqlConnection(connStr))
{
sqlCmd.Connection = sqlconn;
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = storedProcName;
sqlCmd.CommandTimeout = 5000;
foreach (var sqlParam in sqlParameters)
{
sqlCmd.Parameters.Add(sqlParam);
}
using (var sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(dt);
}
}
sqlParameters.Clear();
return dt;
}
//'places the call to the system and returns the data as a datatable
public DataTable GetDataAsDatatable(string connStr, string query)
{
var dt = new DataTable();
var sqlCmd = new SqlCommand();
using (var sqlconn = new SqlConnection(connStr))
{
sqlCmd.Connection = sqlconn;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = query;
sqlCmd.CommandTimeout = 5000;
using (var sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(dt);
}
}
return dt;
}
hopefully this is pretty self explanatory to you, however pass in a list of SQL Parameters, connection string, and the stored procedure name, or use the second one where you pass in the inline SQL and the connection string.
I think you are missing ' in the query. Try this...
string selectQuery = "SELECT * FROM dbo.[" + cmbJobName.Text + "] WHERE ([Job Name] LIKE '" +txtSearchJob.Text+ "' OR [Manufacturer] LIKE '" +txtSearchJob.Text+ "')";

c# Using Parameters.AddWithValue in SqlDataAdapter

How can I use Parameters.AddWithValue with an SqlDataAdapter. Below searching codes.
var da = new SqlDataAdapter("SELECT * FROM annotations WHERE annotation LIKE '%"+txtSearch.Text+"%'", _mssqlCon.connection);
var dt = new DataTable();
da.Fill(dt);
I rewrote the code like this:
SqlDataAdapter da;
da = new SqlDataAdapter("SELECT * FROM annotations WHERE annotation LIKE '%#search%'", _mssqlCon.connection);
da.SelectCommand.Parameters.AddWithValue("#search",txtSearch.Text);
var dt = new DataTable();
da.Fill(dt);
but it failed.
The string used to initialize the SqlDataAdapter becomes the CommandText of the SelectCommand property of the SqlDataAdapter.
You could add parameters to that command with this code
da = new SqlDataAdapter("SELECT * FROM annotations WHERE annotation LIKE #search",
_mssqlCon.connection);
da.SelectCommand.Parameters.AddWithValue("#search","%" + txtSearch.Text + "%");
First, remove the single quote around the parameter placeholder.
Second, add the wildcard character directly in the Value parameter of
AddWithValue
You have asked to use AddWithValue, but remember that, while it is a useful shortcut, there are also numerous drawbacks and all well documented.
First: Can we stop using AddWithValue() already? where the
author discuss how AddWithValue could give back wrong results in your
queries
Second: How Data Access Code Affects Database Performance where
the author presents evidences of strong performance problems for
AddWithValue
So, the same code without AddWithValue and using the Object and Collection Initializers syntax could be written as
da = new SqlDataAdapter("SELECT * FROM annotations WHERE annotation LIKE #search",
_mssqlCon.connection);
da.SelectCommand.Parameters.Add(new SqlParameter
{
ParameterName = "#search",
Value = "%" + txtSearch.Text + "%",
SqlDbType = SqlDbType.NVarChar,
Size = 2000 // Assuming a 2000 char size of the field annotation (-1 for MAX)
});
and, an even more simplified and one liner version of the above is:
da.SelectCommand.Parameters.Add("#search",SqlDbType.NVarChar,2000).Value = "%" + txtSearch.Text + "%";
Use da.SelectCommand.Parameters.Add() instead of cmd.Parameters.Add(), here's a sample for dealing with a stored procedure which takes two parameters and second one is a nullable int parameter:
public DataTable GetData(int par1, int? par2)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
string sql = "StoredProcedure_name";
da.SelectCommand = new SqlCommand(sql, conn);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("#Par1", SqlDbType.Int).Value = par1;
da.SelectCommand.Parameters.Add("#Par2", SqlDbType.Int).Value = (object)par2?? DBNull.Value;
DataSet ds = new DataSet();
da.Fill(ds, "SourceTable_Name");
DataTable dt = ds.Tables["SourceTable_Name"];
//foreach (DataRow row in dt.Rows)
//{
//You can even manipulate your data here
//}
return dt;
}
}
}
Try this:
mySearchString = "Select * From test Where ([title] LIKE '%' + #title + '%')";
cmd.Parameters.Add("#title", SqlDbType.VarChar, 120);
cmd.Parameters("#title").Value = TextBox1.Text;
I use Repeater for show data
int queryString =int.Parse(Request.QueryString["Id"]);
SqlConnection conn =new SqlConnection("server=.; Database=Northwind;
Integrated Security=true;");
try{
conn.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT ProductID, ProductName, UnitPrice, CategoryID FROM Products WHERE CategoryID =#CategoryID", conn);
dataAdapter.SelectCommand.Parameters.Add("#CategoryID", queryString);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
QueryStringProductListRepeater.DataSource = dataSet;
QueryStringProductListRepeater.DataBind();
}
catch{
Response.Write("QueryStringProductListRepeater");
}
finally{
conn.Close();
}

Oracle Connection from C# not reading data

So the following code will not enter the loop to populate my list box. My list box shows "Select All" and test outputs "entering loop". What would cause the try not to fail but the loop not to execute either?
conn.Open();
OracleCommand executeQuery = new OracleCommand(sql, conn);
executeQuery.CommandType = CommandType.Text;
OracleDataReader dr = executeQuery.ExecuteReader();
lstInstructors.Items.Clear();
lstInstructors.Items.Add(new ListItem("Select All", "%"));
string test = "entering loop";
while (dr.Read())
{
test = "start reading items";
lstInstructors.Items.Add(new ListItem(dr.GetValue(0).ToString()));
test += dr.GetValue(0).ToString();
}
Where is the value for "sql" set?
A different way to accomplish populating populating a list box would be to fill a data table then bind it to the list box.
OracleDataAdapter da = new OracleDataAdapter();
DataTable dt = new DataTable();
var sql = "some sql string";
OracleCommand executeQuery = new OracleCommand(sql, conn);
using (da = new OracleDataAdapter(executeQuery))
{
da.Fill(dt);
}
lstInstructors.DataSource = dt;
lstInstructors.DataTextField = "Field Name from sql";
lstInstructors.DataValueField = "Field Value from sql";
lstInstructors.DataBind();
lstInstructors.Items.Insert(0, new ListItem("Choose", "Choose"));
lstInstructors.SelectedValue = "Choose";
be sure to include using System.Data
I've adapted this from the SqlDataAdapter so there may be some syntax differences.

unable to display data using parametrized query with c#

I am trying to display the data using parametrized query
try
{
SqlConnection xconn = new SqlConnection();
xconn.ConnectionString = #" Data Source=servername; Database=master; Trusted_Connection=yes ";
xconn.Open();
SqlCommand ycmd = new SqlCommand ("select * from tablename where column1 = #name", xconn);
ycmd.Parameters.Add("#name", dropdownlist.SelectedValue);
SqlDataAdapter da = new SqlDataAdapter(s,xconn);
SqlCommandBuilder cmdbuilder = new SqlCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
gridview.DataSource = dt;
gridview.DataBind();
}
catch(Exception ex)
{
label.Text = ex.Message + "\n" + ex.StackTrace;
}
How do I get it to work?
Try this:
try
{
SqlConnection xconn = new SqlConnection();
xconn.ConnectionString = #" Data Source=servername; Database=master; Trusted_Connection=yes";
SqlCommand ycmd = new SqlCommand ("select * from tablename where column1 = #name", xconn);
ycmd.Parameters.Add("#name", dropdownlist.SelectedValue);
SqlDataAdapter da = new SqlDataAdapter(ycmd);
DataTable dt = new DataTable();
da.Fill(dt);
gridview.DataSource = dt;
gridview.DataBind();
}
catch(Exception ex)
{
label.Text = ex.Message + "\n" + ex.StackTrace;
}
You don't need to call SqlConnection.Open() when you are using the SqlDataAdapter.Fill() method. In that method it opens up the connection and disposes/closes it when complete. (this isn't the problem, just an FYI)
The way you created your SqlDataAdapter is the problem. You didn't create it with the SqlCommand as a constructor, just the command text. Because of that, you didn't pass in the parameter that was specified in the SqlCommand class.
Let me know if that works. And if that doesn't work, try manually running this query in SSMS to ensure that it actually returns a result set. Also, make sure that your ListControl.SelectedValue property contains something. Do this by debugging and analyze what is stored there.

Categories

Resources