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;
Related
I have a C# code that executes the SQL query. The input of the SQL query comes from a result of a stored procedure. The stored procedure returns a table 6 columns and 25,000 rows. I want to use this stored procedure result as an input to the SQL query. I am storing the stored procedure result in a DataSet. It looks like it's not the correct way to add DataSet results in the query. I need help here experts
Here is what I am doing.
public static void ExecuteSQLQueryTest(string qryName, Boolean nestedQry, string spName)
{
DataTable dtLocalResult = new DataTable();
DataTable dtAzurelResult = new DataTable();
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
List<string> lstring = new List<string>();
aadSQLConnection.Open();
//Connection to CPDashboard DB
var cpdbconnection = new SqlConnection(ConfigurationManager.ConnectionStrings["CATSQL"].ConnectionString);
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = cpdbconnection;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = spName;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
string qryName = "Update A SET A.Environment = B.SC_MD_Environment, A.OSImage = B.SC_APMD_OSImage FROM" + dt + " A"
+ "INNER JOIN[CLOUD].cloudsql.caa.aa_AT_S B ON A.ServerName = B.SC_APMD_MachineName";
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = aadSQLConnection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = qryName;
using (SqlDataAdapter daa = new SqlDataAdapter(cmd))
{
daa.Fill(dt1);
}
}
}
Accessing cell value of your DataTable should be in this format
dt[row index][col index]
And also, we need to put space in between your Table and From
string qryName = "Update A SET A.Environment = B.SC_MD_Environment, A.OSImage = B.SC_APMD_OSImage "
+ "FROM " + dt[0][0] + " A"
+ "INNER JOIN[CLOUD].cloudsql.caa.aa_AT_S B ON A.ServerName = B.SC_APMD_MachineName";
If you are trying to update your datatable from your stored procedure output. you need to use select query for your cloud table instead, then update your datatable.
foreach(DataRow row in dt.Rows)
{
string qryName = "select Environment from [CLOUD].cloudsql.caa.aa_AT_S B where A.ServerName = '"+row["ServerName"].ToString()+"'";
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = aadSQLConnection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = qryName;
using (SqlDataAdapter daa = new SqlDataAdapter(cmd))
{
.....update your datable here
}
}
}
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+ "')";
how can i search data by chekced multiple checkedlistbox when clicking search..?
How can I accomplish filtering data by multiple checkedlistboxes when clicking search?
For example I want to search data that has penyakit = 'Penyakit B' and placeholder = '07'. So when I click search, it should show one row that matches both of these conditions
Here is what I have so far:
MySqlConnection con = new MySqlConnection(MyConnectionString);
con.Open();
try
{
MySqlCommand cmd = con.CreateCommand();
foreach (object itemChecked in chkboxPenyakit.CheckedItems)
{
cmd.CommandText = "Select * FROM tb_pasien where Penyakit = '" + itemChecked.ToString() + "'";
}
MySqlDataAdapter adap = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adap.Fill(ds);
dgvData.DataSource = ds.Tables[0].DefaultView;
}
catch (Exception)
{
throw;
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Clone();
}
}
Following code does not delete a row from dataset and dont update the database....
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection();
con.ConnectionString = cs;
SqlDataAdapter adpt = new SqlDataAdapter("Select *from RegisterInfoB", con);
ds = new DataSet();
adpt.Fill(ds, "RegisterTable");
foreach (DataRow dr in ds.Tables[0].Rows)
{
if (dr["FirstName"] == "praveen")
{
dr.Delete();
}
}
ds.Tables[0].AcceptChanges();
How to resolve this problem...How do I update my sql server database...by deleting a row from dataset..
I hope this will work for you:
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection();
con.ConnectionString = cs;
SqlDataAdapter adpt = new SqlDataAdapter("Select * from RegisterInfoB", con);
DataSet ds = new DataSet();
adpt.Fill(ds, "RegisterTable");
foreach (DataRow dr in ds.Tables[0].Rows)
{
if (dr["FirstName"].ToString().Trim() == "praveen")
{
dr.Delete();
}
}
adpt.Update(ds);
Two Changes
1st: if (dr["FirstName"].ToString().Trim() == "praveen") trimming the blank spaces in your db's FirstName Field.
2nd : use adpt.Update(ds); to update your DB.
Another Way to doing it:
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection();
con.ConnectionString = cs;
string firstName= "praveen"; // this data will get from calling method
SqlDataAdapter adpt = new SqlDataAdapter("Select * from RegisterInfoB", con);
DataSet ds = new DataSet();
adpt.Fill(ds, "RegisterTable");
string deleteQuery = string.Format("Delete from RegisterInfoB where FirstName = '{0}'", firstName);
SqlCommand cmd = new SqlCommand(deleteQuery, con);
adpt.DeleteCommand = cmd;
con.Open();
adpt.DeleteCommand.ExecuteNonQuery();
con.Close();
Similary, you can write query for UpdateCommand and InsertCommand to perform Update and Insert Respectively.
Find rows based on specific column value and delete:
DataRow[] foundRows;
foundRows = ds.Tables["RegisterTable"].Select("FirstName = 'praveen'");
foundRows.Delete();
EDIT: Adding a DeleteCommand to the data adapter (based on example from MSDN)
Note: Need an Id field here instead of FirstName, but I don't know your table structure for RegisterInfoB. Otherwise, we delete everyone named "praveen".
// Create the DeleteCommand.
command = new SqlCommand("DELETE FROM RegisterInfoB WHERE FirstName = #FirstName", con);
// Add the parameters for the DeleteCommand.
parameter = command.Parameters.Add("#FirstName", SqlDbType.NChar, 25, "FirstName");
parameter.SourceVersion = DataRowVersion.Original;
// Assign the DeleteCommand to the adapter
adpt.DeleteCommand = command;
To update a database with a dataset using a data adapter:
try
{
adpt.Update(ds.Tables["RegisterTable"]);
}
catch (Exception e)
{
// Error during Update, add code to locate error, reconcile
// and try to update again.
}
Sources: https://msdn.microsoft.com/en-us/library/xzb1zw3x(v=vs.120).aspx
https://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.120).aspx
hope that resolve the problem,
Try it:
var connectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
var selectQuery = "Select * from RegisterInfoB";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand selectCommand = new SqlCommand(selectQuery, connection);
SqlDataAdapter adapter = new SqlDataAdapter(selectCommand);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
DataSet dataSet = new DataSet();
// you can use the builder to generate the DeleteCommand
adapter.DeleteCommand = builder.GetDeleteCommand();
// or
// adapter.DeleteCommand = new SqlCommand("DELETE FROM RegisterInfoB WHERE Id= #Id", connection);
adapter.Fill(dataSet, "RegisterInfoB");
// you can use the foreach loop
foreach (DataRow current in dataSet.Tables["RegisterInfoB"].Rows)
{
if (current["FirstName"].ToString().ToLower() == "praveen")
{
current.Delete();
}
}
// or the linq expression
// dataSet.Tables["RegisterInfoB"]
// .AsEnumerable()
// .Where(dr => dr["FirstName"].ToString().ToLower().Trim() == "praveen")
// .ToList()
// .ForEach((dr)=> dr.Delete());
var result = adapter.Update(dataSet.Tables["RegisterInfoB"]);
also you can add some events and put a breakpoint to see if the state is changing or if there is an error that prevent changes on the source:
dataSet.Tables["RegisterInfoB"].RowDeleted += (s, e) =>
{
var r = e.Row.RowState;
};
dataSet.Tables["RegisterInfoB"].RowDeleting += (s, e) =>
{
var r = e.Row.RowState;
};
I have a strange problem,
I'm working with win-form which is coding in c#..and sql server
In a form I have a Combo-box which is collected data by the database(say 1).
and later I have to Insert that particular value/member details into another database(say 2)
Here My problem raises,,Once My combo-box any value is inserted into 2nd database,that particular value/member should not visible in the combo-box for the next time on the same day..
Of course Here I'm using datetimepicker..
Here I'm using following code...and Of-course it is wrong..Please Help me
SqlCommand cmd1 = new SqlCommand("select employee_id,Empployee_Name,date from dailyattendance", cn);
SqlDataReader sdr;
DataTable dt = new DataTable();
sdr = cmd1.ExecuteReader();
if (sdr.Read())
{
string employeeid = (string)sdr["employee_id"];
string employeename = (string)sdr["Empployee_Name"];
string date = (string)sdr["date"];
try
{
//cn.Open();
SqlCommand cmd = new SqlCommand("select employee_id,employee_name from Employee_Details", cn);
SqlDataReader sdr1;
DataTable dt1=new DataTable();
sdr1 = cmd.ExecuteReader();
dt1.Load(sdr1);
if (sdr1.Read())
{
string date1=dateTimePicker1.Value.ToString("dd/MM/yyyy");
if ()//here the main problem
{
string employeeid1 = (string)sdr1["employee_id"];
string employeename1 = (string)sdr1["employee_name"];
comboBox1.DisplayMember = employeeid1;
comboBox1.DisplayMember = employeename1;
comboBox1.DataSource=dt1;
cn.Close();
}
}
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection cn = new SqlConnection(connectionString);
cn.Open();
try
{
string dtp = dateTimePicker1.Value.ToString("dd/MM/yyyy");
string query = "select employee_id,employee_name,image_of_employee,image_path from Employee_Details where employee_id not in (select employee_id from dailyattendance where date = '" + dtp + "')";//Here added a new query which is working
SqlCommand cmd = new SqlCommand(query, cn);
SqlDataReader dtr;
dtr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dtr);
foreach (DataRow row in dt.Rows)
{
var name = (string)row["employee_name"];
row["employee_name"] = name.Trim();
}
comboBox1.ValueMember = "employee_id";
comboBox1.DisplayMember = "employee_name";
listBox1.ValueMember = "employee_id";
listBox1.DisplayMember = "employee_name";
comboBox1.DataSource = dt;
listBox1.DataSource = dt;
comboBox1.SelectedItem = null;
listBox1.SelectedItem = null;
cn.Close();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
Simply at query added some workable logic