I'm trying to Iterate through rows in a 2 column table to check 1 field in each row against a Name. Once found I want to code to assign the corresponding Number to the OurNumber variable, and break out of the loop by setting GotTheNumber to true.
Below is the code I'm using:
private void BtnDelete_Click(object sender, EventArgs e)// Sends to ConfirmDeleteEMP Form
{
ConfirmDeleteEMP form = new ConfirmDeleteEMP();
DataTable table = new DataTable();
string connstring = #"Provider = Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\HoliPlanData.accdb;Persist Security Info=False";
using (OleDbConnection conn = new OleDbConnection(connstring))
{
string query = "SELECT PayrollNo, (FirstName + ' ' + LastName) AS NAME FROM [Employee]";
OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
adapter.Fill(table);
}
string SelectedName = DropBoxEmp.Text;
bool GotTheNumber = false;
int OurNumber = 0;
while (!GotTheNumber)
{
foreach (DataRow ThisRow in table.Rows)
{
if (SelectedName = (table.Rows[ThisRow]))
{
OurNumber = ///THATNUMBER///;
GotTheNumber = true;
}
}
}
MessageBox.Show(SelectedName);
var GoodNumber = (table.Rows[OurNumber]["PayrollNo"].ToString());
form.PassValueName = SelectedName;
form.PassSelectedPayroll = GoodNumber;
form.Tag = this;
form.Show(this);
Hide();
}
I don't know where to go from the If statement, so any help would be greatly appreciated.
Looping through the rows in your client program is exactly what you don't want to do. Let the database do that work for you. Try this:
private void BtnDelete_Click(object sender, EventArgs e)// Sends to ConfirmDeleteEMP Form
{
object result;
string query = "SELECT PayrollNo FROM [Employee] WHERE FirstName + ' ' + LastName = ?";
string connstring = #"Provider = Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\HoliPlanData.accdb;Persist Security Info=False";
using (OleDbConnection conn = new OleDbConnection(connstring))
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
//guessing at type and length here
cmd.Parameters.Add("?", OleDbType.VarWChar, 50).Value = DropBoxEmp.Text;
conn.Open();
result = cmd.ExecuteScalar();
}
if (result != null && result != DBNull.Value)
{
ConfirmDeleteEMP form = new ConfirmDeleteEMP();
form.PassValueName = DropBoxEmp.Text;
form.PassSelectedPayroll = (int)result;
form.Tag = this;
form.Show(this);
Hide();
}
}
If you really want to loop through the rows against all reason (it's slower, requires writing more code, and it's more error-prone), you can do this:
private void BtnDelete_Click(object sender, EventArgs e)// Sends to ConfirmDeleteEMP Form
{
DataTable table = new DataTable();
string query = "SELECT PayrollNo, (FirstName + ' ' + LastName) AS NAME FROM [Employee]";
string connstring = #"Provider = Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\HoliPlanData.accdb;Persist Security Info=False";
using (OleDbConnection conn = new OleDbConnection(connstring))
{
OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
adapter.Fill(table);
}
int PayrollNumber = 0;
foreach (DataRow ThisRow in table.Rows)
{
if (DropBoxEmp.Text == ThisRow["NAME"])
{
PayrollNumber = (int)ThisRow["PayrollNo"];
break;
}
}
//the whole loop could also be consolidated to this:
//PayrollNumber = (int)table.Rows.First(r => r["NAME"] == DropBoxEmp.Text)["PayrollNo"];
ConfirmDeleteEMP form = new ConfirmDeleteEMP();
form.PassValueName = DropBoxEmp.Text;
form.PassSelectedPayroll = PayrollNumber ;
form.Tag = this;
form.Show(this);
Hide();
}
Hm, hard to guess what exactly your problem is. But I think you just want to get the PayrollNo from the current row, aren't you?
Regarding the line further down ...
var GoodNumber = (table.Rows[OurNumber]["PayrollNo"].ToString());
... I think you could just call:
if (...)
{
OurNumber = ThisRow["PayrollNo"].ToString();
GotTheNumber = true;
}
However, I have no clue what you are doing with the following if-condition and if this really does what you want it to do:
if (SelectedName = (table.Rows[ThisRow]))
{
...
}
Related
I am a beginner in C# and created a database in a Windows Forms App for a customer data, the function of it is to take the user's phone number and then search the table and then if it is found then populate the data fields with the information; otherwise it needs to add the new customer to the table.
When I run the code I get an error
System.ArgumentException: 'Keyword not supported: 'data source(localdb)\mssqlocaldb;attachdbfilename'.'
This is my code:
DataTable TableCust;
SqlConnection cnCust;
SqlDataAdapter dataCust;
DataGrid dtGridCust;
public bool buttonClicked = false;
private static int CurrentOrder = 1000;
private int i = 0;
Validation v = new Validation();
public frmPizzaPetes()
{
InitializeComponent();
}
string dataSource;
string SqlParms;
private void Form1_Load(object sender, EventArgs e)
{
btnAccept.Enabled = false;
lblOrderNo.Text = CurrentOrder.ToString();
Price();
//
dataSource = #"Data Source(LocalDB)\MSSQLocalDB;AttachDbFilename=|C:\Users\tyada\DATABASE\Pizza.mdf;";
SqlParms = "Integrated Securtiy=True; Connect Timeout==30";
string SqlCust = "select * from Customers";
string strConn = dataSource + SqlParms;
cnCust = new SqlConnection(strConn);
cnCust.Open();
TableCust = new DataTable();
dtGridCust.DataSource = TableCust;
}
public bool ifCustIsFound()
{
bool tester=false;
string SqlCustomer = "SELECT*FROM Customers WHERE CustPhone= '" + mtbPhone.Text + "';";
dataCust = new SqlDataAdapter(SqlCustomer, cnCust);
dataCust.Fill(TableCust);
if (TableCust.Rows.Count > 0)
{
txtName.Text = TableCust.Rows[0]["CustName"].ToString();
txtAddress.Text = TableCust.Rows[0]["CustAddress"].ToString();
txtApt.Text = TableCust.Rows[0]["CustSuite"].ToString();
txtCity.Text = TableCust.Rows[0]["CustCity"].ToString();
mtbZip.Text = TableCust.Rows[0]["CustZip"].ToString();
cboState.Text = TableCust.Rows[0]["CustState"].ToString();
// dtGridCust.DataSource = TableCust;
}
else
{
DialogResult dlg=MessageBox.Show("Add Customer?","Customer not found", MessageBoxButtons.YesNo);
if (dlg == DialogResult.Yes)
{
string strConn = dataSource + SqlParms;
SqlDataAdapter adaptSQL = new SqlDataAdapter(strSQL, strConn);
SqlCommand cmdCust = new SqlCommand();
SqlCommandBuilder cmdBld = new SqlCommandBuilder(adaptSQL);
DataRow newCust;
newCust = TableCust.NewRow();
newCust["CustPhone"] = mtbPhone.Text;
newCust["CustName"] = txtName.Text;
newCust["CustAddress1"] = txtAddress.Text;
newCust["CustAddress2"] = txtApt.Text;
newCust["CustCity"] = txtCity.Text;
newCust["CustState"] = cboState.Text;
newCust["CustZip"] = mtbZip.Text;
try
{
TableCust.Rows.Add(newCust);
cmdBld.GetUpdateCommand();
adaptSQL.Update(TableCust);
MessageBox.Show("Customer Added!");
}
catch (SqlException)
{
MessageBox.Show("Customer Add Failed!");
}
}
txtName.Focus();
}
return tester;
}
it seems "=" is missing in data source. Try this.
private void Form1_Load(object sender, EventArgs e)
{
btnAccept.Enabled = false;
lblOrderNo.Text = CurrentOrder.ToString();
Price();
//
dataSource = #"Data Source =(LocalDB)\MSSQLocalDB;AttachDbFilename=|C:\Users\tyada\DATABASE\Pizza.mdf;";
SqlParms = "Integrated Securtiy=True; Connect Timeout==30";
string SqlCust = "select * from Customers";
string strConn = dataSource + SqlParms;
cnCust = new SqlConnection(strConn);
cnCust.Open();
TableCust = new DataTable();
dtGridCust.DataSource = TableCust;
}
I am getting data from excel and showing it in DataGridWiew.
I have two textboxes, one is for starting index for first record and other is for last record.
Code works fine. But lets suppose starting record is 1 and ending is 10 when I change 10 to 1 or 2 it gives me an error in this line:
adapter.Fill(dataTable);
Full Code is below:
public DataSet Parse(string fileName)
{
string connectionString = string.Format("provider = Microsoft.Jet.OLEDB.4.0; data source = {0}; Extended Properties = Excel 8.0;", fileName);
DataSet data = new DataSet();
foreach (var sheetName in GetExcelSheetNames(connectionString))
{
using (OleDbConnection con = new OleDbConnection(connectionString))
{
string query = "";
var dataTable = new DataTable();
if(tbStarting.Text.Trim()=="" && tbEnding.Text.Trim() == "")
{
query = string.Format("SELECT * FROM [{0}]", sheetName);
}
else
{
query = string.Format("SELECT * FROM [{0}] where SrNo between " + int.Parse(tbStarting.Text.Trim()) + " and " + int.Parse(tbEnding.Text.Trim()) + " order by SrNo", sheetName);
}
con.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(query, con);
adapter.Fill(dataTable);
data.Tables.Add(dataTable);
con.Close();
}
}
return data;
}
static string[] GetExcelSheetNames(string connectionString)
{
OleDbConnection con = null;
DataTable dt = null;
con = new OleDbConnection(connectionString);
con.Open();
dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheetNames = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheetNames[i] = row["TABLE_NAME"].ToString();
i++;
}
return excelSheetNames;
}
Why this is happening please help me?
Looking at the code, it seems that your procedure is working when you ask to retrieve all the record in each table. But you are not showing which table (Sheet) is actually used afterwars.
Chances are, you are using the first one only.
When you submit some parameters, only one of the tables (Sheets) can fulfill those requirements. The other(s) don't, possibly because a field named [SrNo] is not present.
This causes the More Parameters Required error when trying to apply a filter.
Not related to the error, but worth noting: you don't need to recreate the whole DataSet + DataTables to filter your DataSources.
The DataSet.Tables[N].DefaultView.RowFilter can be used to get the same result without destroying all the objects each time a filter is required.
RowFilter has some limitations in the language (e.g. does not support BETWEEN, Field >= Value1 AND Field <= Value2 must be used), but it's quite effective.
This is a possible setup:
(xDataSet is a placeholder for your actual DataSet)
//Collect the values in the TextBoxes in a string array
private void button1_Click(object sender, EventArgs e)
{
string[] Ranges = new string[] { tbStarting.Text.Trim(), tbEnding.Text.Trim() };
if (xDataSet != null)
FilterDataset(Ranges);
}
private void FilterDataset(string[] Ranges)
{
if (string.IsNullOrEmpty(Ranges[0]) & string.IsNullOrEmpty(Ranges[1]))
xDataSet.Tables[0].DefaultView.RowFilter = null;
else if (string.IsNullOrEmpty(Ranges[0]) | string.IsNullOrEmpty(Ranges[1]))
return;
else if (int.Parse(Ranges[0]) < int.Parse(Ranges[1]))
xDataSet.Tables[0].DefaultView.RowFilter = string.Format("SrNo >= {0} AND SrNo <= {1}", Ranges[0], Ranges[1]);
else
xDataSet.Tables[0].DefaultView.RowFilter = string.Format("SrNo = {0}", Ranges[0]);
this.dataGridView1.Update();
}
I've modified your code you code a bit to handle those requirements.
(I've left here those filters anyway; they're not used, but if you still want them, they are in a working condition)
DataSet xDataSet = new DataSet();
string WorkBookPath = #"[Excel WorkBook Path]";
//Query one Sheet only. More can be added if necessary
string[] WBSheetsNames = new string[] { "Sheet1" };
//Open the Excel document and assign the DataSource to a dataGridView
xDataSet = Parse(WorkBookPath, WBSheetsNames, null);
dataGridView1.DataSource = xDataSet.Tables[0];
dataGridView1.Refresh();
public DataSet Parse(string fileName, string[] WorkSheets, string[] ranges)
{
if (!File.Exists(fileName)) return null;
string connectionString = string.Format("provider = Microsoft.ACE.OLEDB.12.0; " +
"data source = {0}; " +
"Extended Properties = \"Excel 12.0;HDR=YES\"",
fileName);
DataSet data = new DataSet();
string query = string.Empty;
foreach (string sheetName in GetExcelSheetNames(connectionString))
{
foreach (string WorkSheet in WorkSheets)
if (sheetName == (WorkSheet + "$"))
{
using (OleDbConnection con = new OleDbConnection(connectionString))
{
DataTable dataTable = new DataTable();
if ((ranges == null) ||
(string.IsNullOrEmpty(ranges[0]) || string.IsNullOrEmpty(ranges[1])) ||
(int.Parse(ranges[0]) > int.Parse(ranges[1])))
query = string.Format("SELECT * FROM [{0}]", sheetName);
else if ((int.Parse(ranges[0]) == int.Parse(ranges[1])))
query = string.Format("SELECT * FROM [{0}] WHERE SrNo = {1}", sheetName, ranges[0]);
else
query = string.Format("SELECT * FROM [{0}] WHERE (SrNo BETWEEN {1} AND {2}) " +
"ORDER BY SrNo", sheetName, ranges[0], ranges[1]);
con.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(query, con);
adapter.Fill(dataTable);
data.Tables.Add(dataTable);
};
}
}
return data;
}
static string[] GetExcelSheetNames(string connectionString)
{
string[] excelSheetNames = null;
using (OleDbConnection con = new OleDbConnection(connectionString))
{
con.Open();
using (DataTable dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null))
{
if (dt != null)
{
excelSheetNames = new string[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
excelSheetNames[i] = dt.Rows[i]["TABLE_NAME"].ToString();
}
}
}
}
return excelSheetNames;
}
I'm having trouble inserting data into my table called "client" in my database called "vet".
I'm trying to do the connection manually as opposed to using the database wizard. I want to do it this way so that i can hide the majority of my code in a separate class.
I have a feeling I have the logic for this all wrong as I'm not making use of a data set, I was hoping someone could point me in the right direction.
This is for a school assignment and not for real world use. I have read a number of similar posts but am still unable to come to a solution.
public void CommitToDatabase()
{
using (var con = new SqlConnection(CLSDatabaseDetails.GlobalConnectionString))
{
DataTable client = new DataTable();
DataSet ds = new DataSet();
string commandString = "SELECT * FROM client";
SqlCommand cmd = new SqlCommand(commandString, con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(client);
DataRow newClientRow = ds.Tables["client"].NewRow();
newClientRow["ClientID"] = ClientID;
newClientRow["FirstName"] = FirstName;
newClientRow["LastName"] = LastName;
newClientRow["Phone"] = PhoneNumber;
newClientRow["CAddress"] = Address;
newClientRow["Email"] = Email;
newClientRow["CUsername"] = Username;
newClientRow["CPassword"] = Password;
client.Rows.Add(newClientRow);
da.Update(client);
}
}
A DataSet is a collection of DataTables. In your example, you're only referring to one table. The SqlDataAdapter.Fill method will populate either DataSet or DataTable. You're calling da.Fill(client) which is fine - it will fill the DataTable client. You could also call da.Fill(ds, "client") which will fill the DataSet ds. You can then extract your table via ds.Tables["client"]. Using a DataSet in this example is overkill, but you can show your tutor how a DataSet works.
You're filling the DataTable but then adding the new row with reference to the DataSet. But in your example, the DataSet ds has nothing in it, because you filled the DataTable not the DataSet. Try this:
DataSet ds = new DataSet();
string commandString = "SELECT TOP 0 * FROM client";
SqlCommand cmd = new SqlCommand(commandString, con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlCommandBuilder builder = new SqlCommandBuilder(da);
da.Fill(ds, "client");
DataTable client = ds.Tables["client"];
DataRow newClientRow = client.NewRow();
... ... ...
client.Rows.Add(newClientRow);
builder.GetInsertCommand();
da.Update(client);
If you only want to insert a row, you don't need to SELECT all the rows. If you SELECT TOP 0 * from client you'll get the column names (which you need) but without the overhead of returning all the rows.
Try something like this:
public void CommitToDatabase()
{
using (var con = new SqlConnection(CLSDatabaseDetails.GlobalConnectionString))
{
DataTable client = new DataTable();
string commandString = "SELECT * FROM client";
SqlCommand cmd = new SqlCommand(commandString, con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(client);
DataRow newClientRow = client.NewRow();
newClientRow["ClientID"] = ClientID;
newClientRow["FirstName"] = FirstName;
newClientRow["LastName"] = LastName;
newClientRow["Phone"] = PhoneNumber;
newClientRow["CAddress"] = Address;
newClientRow["Email"] = Email;
newClientRow["CUsername"] = Username;
newClientRow["CPassword"] = Password;
client.Rows.Add(newClientRow);
da.Update(client);
}
}
I can't tell what the source of your data is. Anyway, here are two examples of moving data from a CSV file to SQL Server and from a DataGridView to SQL Server.
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Data.SqlClient;
using System.IO;
using Microsoft.VisualBasic.FileIO;
using System.Data.Odbc;
using System.Data.OleDb;
using System.Configuration;
public class Form1
{
private void Button1_Click(System.Object sender, System.EventArgs e)
{
dynamic headers = (from header in DataGridView1.Columns.Cast<DataGridViewColumn>()header.HeaderText).ToArray;
dynamic rows = from row in DataGridView1.Rows.Cast<DataGridViewRow>()where !row.IsNewRowArray.ConvertAll(row.Cells.Cast<DataGridViewCell>.ToArray, c => c.Value != null ? c.Value.ToString : "");
string str = "";
using (IO.StreamWriter sw = new IO.StreamWriter("C:\\Users\\Excel\\Desktop\\OrdersTest.csv")) {
sw.WriteLine(string.Join(",", headers));
//sw.WriteLine(String.Join(","))
foreach (void r_loopVariable in rows) {
r = r_loopVariable;
sw.WriteLine(string.Join(",", r));
}
sw.Close();
}
}
private void Button2_Click(System.Object sender, System.EventArgs e)
{
//Dim m_strConnection As String = "server='Server_Name';Initial Catalog='Database_Name';Trusted_Connection=True;"
//Catch ex As Exception
// MessageBox.Show(ex.ToString())
//End Try
//Dim objDataset1 As DataSet()
//Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
//Dim da As OdbcDataAdapter
System.Windows.Forms.OpenFileDialog OpenFile = new System.Windows.Forms.OpenFileDialog();
// Does something w/ the OpenFileDialog
string strFullPath = null;
string strFileName = null;
TextBox tbFile = new TextBox();
// Sets some OpenFileDialog box options
OpenFile.Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*";
// Shows only .csv files
OpenFile.Title = "Browse to file:";
// Title at the top of the dialog box
// Makes the open file dialog box show up
if (OpenFile.ShowDialog() == DialogResult.OK) {
strFullPath = OpenFile.FileName;
// Assigns variable
strFileName = Path.GetFileName(strFullPath);
// Checks to see if they've picked a file
if (OpenFile.FileNames.Length > 0) {
tbFile.Text = strFullPath;
// Puts the filename in the textbox
// The connection string for reading into data connection form
string connStr = null;
connStr = "Driver={Microsoft Text Driver (*.txt; *.csv)}; Dbq=" + Path.GetDirectoryName(strFullPath) + "; Extensions=csv,txt ";
// Sets up the data set and gets stuff from .csv file
OdbcConnection Conn = new OdbcConnection(connStr);
DataSet ds = default(DataSet);
OdbcDataAdapter DataAdapter = new OdbcDataAdapter("SELECT * FROM [" + strFileName + "]", Conn);
ds = new DataSet();
try {
DataAdapter.Fill(ds, strFileName);
// Fills data grid..
DataGridView1.DataSource = ds.Tables(strFileName);
// ..according to data source
// Catch and display database errors
} catch (OdbcException ex) {
OdbcError odbcError = default(OdbcError);
foreach ( odbcError in ex.Errors) {
MessageBox.Show(ex.Message);
}
}
// Cleanup
OpenFile.Dispose();
Conn.Dispose();
DataAdapter.Dispose();
ds.Dispose();
}
}
}
private void Button3_Click(System.Object sender, System.EventArgs e)
{
SqlConnection cnn = default(SqlConnection);
string connectionString = null;
string sql = null;
connectionString = "data source='Server_Name';" + "initial catalog='Database_Name';Trusted_Connection=True";
cnn = new SqlConnection(connectionString);
cnn.Open();
sql = "SELECT * FROM [Order Details]";
SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
DataSet ds = new DataSet();
dscmd.Fill(ds);
DataGridView1.DataSource = ds.Tables(0);
cnn.Close();
}
private void ProductsDataGridView_CellFormatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == DataGridView1.Columns(3).Index && e.Value != null) {
//
if (Convert.ToInt32(e.Value) < 10) {
e.CellStyle.BackColor = Color.OrangeRed;
e.CellStyle.ForeColor = Color.LightGoldenrodYellow;
}
//
}
//
}
//Private Sub ProductsDataGridView_CellFormatting(ByVal sender As Object, _
// ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) _
// Handles DataGridView1.CellFormatting
// '
// If e.ColumnIndex = DataGridView1.Columns("DataGridViewTextBoxColumn8").Index _
// AndAlso e.Value IsNot Nothing Then
// '
// If CInt(e.Value) < 5 Then
// e.CellStyle.BackColor = Color.OrangeRed
// e.CellStyle.ForeColor = Color.LightGoldenrodYellow
// End If
// '
// End If
// '
//End Sub
//If e.ColumnIndex = ProductsDataGridView.Columns(4).Index _
//AndAlso e.Value IsNot Nothing Then
//'
// If CInt(e.Value) = 0 Then
// e.CellStyle.BackColor = Color.OrangeRed
// e.CellStyle.ForeColor = Color.LightGoldenrodYellow
// End If
//End If
// ''To (you need to change the column name)
// If e.ColumnIndex = ProductsDataGridView.Columns("YourColumnName").Index _
// AndAlso e.Value IsNot Nothing Then
//'
// If CInt(e.Value) = 0 Then
// e.CellStyle.BackColor = Color.OrangeRed
// e.CellStyle.ForeColor = Color.LightGoldenrodYellow
// End If
//End If
private void Button4_Click(System.Object sender, System.EventArgs e)
{
DataTable tblReadCSV = new DataTable();
tblReadCSV.Columns.Add("FName");
tblReadCSV.Columns.Add("LName");
tblReadCSV.Columns.Add("Department");
TextFieldParser csvParser = new TextFieldParser("C:\\Users\\Excel\\Desktop\\Employee.txt");
csvParser.Delimiters = new string[] { "," };
csvParser.TrimWhiteSpace = true;
csvParser.ReadLine();
while (!(csvParser.EndOfData == true)) {
tblReadCSV.Rows.Add(csvParser.ReadFields());
}
SqlConnection con = new SqlConnection("Server='Server_Name';Database='Database_Name';Trusted_Connection=True;");
string strSql = "Insert into Employee(FName,LName,Department) values(#Fname,#Lname,#Department)";
//Dim con As New SqlConnection(strCon)
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strSql;
cmd.Connection = con;
cmd.Parameters.Add("#Fname", SqlDbType.VarChar, 50, "FName");
cmd.Parameters.Add("#Lname", SqlDbType.VarChar, 50, "LName");
cmd.Parameters.Add("#Department", SqlDbType.VarChar, 50, "Department");
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.InsertCommand = cmd;
int result = dAdapter.Update(tblReadCSV);
}
private void Button5_Click(System.Object sender, System.EventArgs e)
{
string SQLConnectionString = "Data Source=Excel-PC\\SQLEXPRESS;" + "Initial Catalog=Northwind;" + "Trusted_Connection=True";
// Open a connection to the AdventureWorks database.
using (SqlConnection SourceConnection = new SqlConnection(SQLConnectionString)) {
SourceConnection.Open();
// Perform an initial count on the destination table.
SqlCommand CommandRowCount = new SqlCommand("SELECT COUNT(*) FROM dbo.Orders;", SourceConnection);
long CountStart = System.Convert.ToInt32(CommandRowCount.ExecuteScalar());
Console.WriteLine("Starting row count = {0}", CountStart);
// Get data from the source table as a AccessDataReader.
//Dim ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
// "Data Source=" & "C:\Users\Excel\Desktop\OrdersTest.txt" & ";" & _
// "Extended Properties=" & "text;HDR=Yes;FMT=Delimited"","";"
string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + "C:\\Users\\Excel\\Desktop\\" + ";" + "Extended Properties=\"Text;HDR=No\"";
System.Data.OleDb.OleDbConnection TextConnection = new System.Data.OleDb.OleDbConnection(ConnectionString);
OleDbCommand TextCommand = new OleDbCommand("SELECT * FROM OrdersTest#csv", TextConnection);
TextConnection.Open();
OleDbDataReader TextDataReader = TextCommand.ExecuteReader(CommandBehavior.SequentialAccess);
// Open the destination connection.
using (SqlConnection DestinationConnection = new SqlConnection(SQLConnectionString)) {
DestinationConnection.Open();
// Set up the bulk copy object.
// The column positions in the source data reader
// match the column positions in the destination table,
// so there is no need to map columns.
using (SqlBulkCopy BulkCopy = new SqlBulkCopy(DestinationConnection)) {
BulkCopy.DestinationTableName = "dbo.Orders";
try {
// Write from the source to the destination.
BulkCopy.WriteToServer(TextDataReader);
} catch (Exception ex) {
Console.WriteLine(ex.Message);
} finally {
// Close the AccessDataReader. The SqlBulkCopy
// object is automatically closed at the end
// of the Using block.
TextDataReader.Close();
}
}
// Perform a final count on the destination table
// to see how many rows were added.
long CountEnd = System.Convert.ToInt32(CommandRowCount.ExecuteScalar());
//Console.WriteLine("Ending row count = {0}", CountEnd)
//Console.WriteLine("{0} rows were added.", CountEnd - CountStart)
}
}
//Dim FILE_NAME As String = "C:\Users\Excel\Desktop\OrdersTest.csv"
//Dim TextLine As String
//If System.IO.File.Exists(FILE_NAME) = True Then
// Dim objReader As New System.IO.StreamReader(FILE_NAME)
// Do While objReader.Peek() <> -1
// TextLine = TextLine & objReader.ReadLine() & vbNewLine
// Loop
//Else
// MsgBox("File Does Not Exist")
//End If
//Dim cn As New SqlConnection("Data Source=Excel-PC\SQLEXPRESS;Initial Catalog=Northwind;Trusted_Connection=True;")
//Dim cmd As New SqlCommand
//cmd.Connection = cn
//cmd.Connection.Close()
//cmd.Connection.Open()
//cmd.CommandText = "INSERT INTO Orders (OrderID,CustomerID,EmployeeID,OrderDate,RequiredDate,ShippedDate,ShipVia,Freight,ShipName,ShipAddress,ShipCity,ShipRegion,ShipPostalCode,ShipCountry) values & OrdersTest.csv"
//cmd.ExecuteNonQuery()
//cmd.Connection.Close()
}
private void Button6_Click(System.Object sender, System.EventArgs e)
{
// Define the Column Definition
DataTable dt = new DataTable();
dt.Columns.Add("OrderID", typeof(int));
dt.Columns.Add("CustomerID", typeof(string));
dt.Columns.Add("EmployeeID", typeof(int));
dt.Columns.Add("OrderDate", typeof(System.DateTime));
dt.Columns.Add("RequiredDate", typeof(System.DateTime));
dt.Columns.Add("ShippedDate", typeof(System.DateTime));
dt.Columns.Add("ShipVia", typeof(int));
dt.Columns.Add("Freight", typeof(decimal));
dt.Columns.Add("ShipName", typeof(string));
dt.Columns.Add("ShipAddress", typeof(string));
dt.Columns.Add("ShipCity", typeof(string));
dt.Columns.Add("ShipRegion", typeof(string));
dt.Columns.Add("ShipPostalCode", typeof(string));
dt.Columns.Add("ShipCountry", typeof(string));
using (cn == new SqlConnection("Server='Server_Name';Database='Database_Name';Trusted_Connection=True;")) {
cn.Open();
Microsoft.VisualBasic.FileIO.TextFieldParser reader = default(Microsoft.VisualBasic.FileIO.TextFieldParser);
string[] currentRow = null;
DataRow dr = default(DataRow);
string sqlColumnDataType = null;
reader = My.Computer.FileSystem.OpenTextFieldParser("C:\\Users\\Excel\\Desktop\\OrdersTest.csv");
reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited;
reader.Delimiters = new string[] { "," };
while (!reader.EndOfData) {
try {
currentRow = reader.ReadFields();
dr = dt.NewRow();
for (currColumn = 0; currColumn <= dt.Columns.Count - 1; currColumn++) {
sqlColumnDataType = dt.Columns(currColumn).DataType.Name;
switch (sqlColumnDataType) {
case "String":
if (string.IsNullOrEmpty(currentRow(currColumn))) {
dr.Item(currColumn) = "";
} else {
dr.Item(currColumn) = Convert.ToString(currentRow(currColumn));
}
break;
case "Decimal":
if (string.IsNullOrEmpty(currentRow(currColumn))) {
dr.Item(currColumn) = 0;
} else {
dr.Item(currColumn) = Convert.ToDecimal(currentRow(currColumn));
}
break;
case "DateTime":
if (string.IsNullOrEmpty(currentRow(currColumn))) {
dr.Item(currColumn) = "";
} else {
dr.Item(currColumn) = Convert.ToDateTime(currentRow(currColumn));
}
break;
}
}
dt.Rows.Add(dr);
} catch (Microsoft.VisualBasic.FileIO.MalformedLineException ex) {
Interaction.MsgBox("Line " + ex.Message + "is not valid." + Constants.vbCrLf + "Terminating Read Operation.");
reader.Close();
reader.Dispose();
//Return False
} finally {
dr = null;
}
}
using (SqlBulkCopy copy = new SqlBulkCopy(cn)) {
copy.DestinationTableName = "[dbo].[Orders]";
copy.WriteToServer(dt);
}
}
}
public static bool GetCsvData(string CSVFileName, ref DataTable CSVTable)
{
Microsoft.VisualBasic.FileIO.TextFieldParser reader = default(Microsoft.VisualBasic.FileIO.TextFieldParser);
string[] currentRow = null;
DataRow dr = default(DataRow);
string sqlColumnDataType = null;
reader = My.Computer.FileSystem.OpenTextFieldParser(CSVFileName);
reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited;
reader.Delimiters = new string[] { "," };
while (!reader.EndOfData) {
try {
currentRow = reader.ReadFields();
dr = CSVTable.NewRow();
for (currColumn = 0; currColumn <= CSVTable.Columns.Count - 1; currColumn++) {
sqlColumnDataType = CSVTable.Columns(currColumn).DataType.Name;
switch (sqlColumnDataType) {
case "String":
if (string.IsNullOrEmpty(currentRow(currColumn))) {
dr.Item(currColumn) = "";
} else {
dr.Item(currColumn) = Convert.ToString(currentRow(currColumn));
}
break;
case "Decimal":
if (string.IsNullOrEmpty(currentRow(currColumn))) {
dr.Item(currColumn) = 0;
} else {
dr.Item(currColumn) = Convert.ToDecimal(currentRow(currColumn));
}
break;
case "DateTime":
if (string.IsNullOrEmpty(currentRow(currColumn))) {
dr.Item(currColumn) = "";
} else {
dr.Item(currColumn) = Convert.ToDateTime(currentRow(currColumn));
}
break;
}
}
CSVTable.Rows.Add(dr);
} catch (Microsoft.VisualBasic.FileIO.MalformedLineException ex) {
Interaction.MsgBox("Line " + ex.Message + "is not valid." + Constants.vbCrLf + "Terminating Read Operation.");
reader.Close();
reader.Dispose();
return false;
} finally {
dr = null;
}
}
reader.Close();
reader.Dispose();
return true;
}
}
//=======================================================
//Service provided by Telerik (www.telerik.com)
//Conversion powered by NRefactory.
//Twitter: #telerik
//Facebook: facebook.com/telerik
//=======================================================
Hi Guys I am trying to understand how to save and edited row to the database
private void BudgetGrid_RowEditEnding(object sender,
DataGridRowEditEndingEventArgs e)
{
SqlCommand gridcmd = new SqlCommand();
SqlConnection rwConn = null;
rwConn = new SqlConnection("server=localhost;" +
"Trusted_Connection=yes;" + "database=Production; " + "connection
timeout=30");
gridcmd.Connection = rwConn;
rwConn.Open();
//gridcmd.CommandText =
//"SELECT Id, Name, Quantity, Rate, Time FROM Budget";
gridcmd.CommandText =
"UPDATE Budget SET Id = #id, Name = #Name, " +
"Quantity = #Qty, Rate = #Rte WHERE Time = #Time";
SqlDataAdapter gridda = new SqlDataAdapter(gridcmd);
string strId = "#id".ToString();
int intID;
bool bintID = Int32.TryParse(strId, out intID);
string strName = "#Name".ToString();
string strQty = "#Qty".ToString();
int intQty;
bool bintQty = Int32.TryParse(strQty, out intQty);
string strRte = "#Rte".ToString();
int intRte;
bool bintRte = Int32.TryParse(strRte, out intRte);
string strTime = "#Time".ToString();
gridda.SelectCommand.Parameters.Add(
new SqlParameter("#id", SqlDbType.Int));
gridda.SelectCommand.Parameters["#id"].SqlValue = intID;
gridda.SelectCommand.Parameters.Add(
new SqlParameter("#Name", SqlDbType.VarChar));
gridda.SelectCommand.Parameters["#Name"].SqlValue = strName;
gridda.SelectCommand.Parameters.Add(
new SqlParameter("#Qty", SqlDbType.Int));
gridda.SelectCommand.Parameters["#Qty"].SqlValue = strQty;
gridda.SelectCommand.Parameters.Add(
new SqlParameter("#Rte", SqlDbType.Int));
gridda.SelectCommand.Parameters["#Rte"].SqlValue = strRte;
gridda.SelectCommand.Parameters.Add(
new SqlParameter("#Time", SqlDbType.VarChar));
gridda.SelectCommand.Parameters["#Time"].SqlValue = strTime;
DataTable griddt = new DataTable("Budget");
gridda.Fill(griddt);
gridda.UpdateCommand =
new SqlCommandBuilder(gridda).GetUpdateCommand();
BudgetGrid.ItemsSource = griddt.DefaultView;
gridda.Update(griddt);
rwConn.Close();
}
it displays fine. I can edit its but when I click on the other tab it does not update it goes back to the original data.
Most of the code I have been going through its either out dated.. or not what I am looking for.
so here is the database
and here is the app
so basically if i hit tab to the next row. under the event BudgetGrid_RowEditEnding it should update the database.. but now its not.
Just copy below codes. I've created all the thing of you and tested successfully. Rather than the first way, I tried to let you go more popular way. Therefore, it took me time to adopt..
Hope this helps you !
SqlDataAdapter da;
DataTable dt;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
SqlConnection Conn = new SqlConnection();
Conn.ConnectionString = yourConnectionString;
Conn.Open();
SqlCommand gridcomm = new SqlCommand();
gridcomm.Connection = Conn;
gridcomm.CommandText = "SELECT Id, Name, Quantity, Rate, Time FROM Budget";
da = new SqlDataAdapter(gridcomm);
SqlDataReader gridreader = gridcomm.ExecuteReader();
while (gridreader.Read())
{
}
gridreader.Close();
dt= new DataTable("Budget");
da.Fill(dt);
dataGrid_Budget.ItemsSource = dt.DefaultView;
Conn.Close();
}
private void dataGrid_Budget_RowEditEnding(object sender, System.Windows.Controls.DataGridRowEditEndingEventArgs e)
{
DataGridRow editedrow = e.Row;
int row_index = (DataGrid)sender).ItemContainerGenerator.IndexFromContainer(editedrow);
for (int k=0;k< 5;k++)
{
DataGridCell cell = GetCell(row_index, k);
TextBlock tb = cell.Content as TextBlock;
if (k==1)
{
dt.Rows[row_index][k] = tb.Text;
}
else if (k == 4)
{
if (tb.Text != "")
{
dt.Rows[row_index][k] = Convert.ToDateTime(tb.Text);
}
}
else
{
dt.Rows[row_index][k] = Convert.ToInt32(tb.Text);
}
}
da.UpdateCommand = new SqlCommandBuilder(da).GetUpdateCommand();
da.Update(dt);
}
public DataGridCell GetCell(int row, int column)
{
DataGridRow rowContainer = GetRow(row);
if (rowContainer != null)
{
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
if (cell == null)
{
dataGrid_Budget.ScrollIntoView(rowContainer, dataGrid_Budget.Columns[column]);
cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
}
return cell;
}
return null;
}
public DataGridRow GetRow(int index)
{
DataGridRow row = (DataGridRow)dataGrid_Budget.ItemContainerGenerator.ContainerFromIndex(index);
if (row == null)
{
dataGrid_Budget.UpdateLayout();
dataGrid_Budget.ScrollIntoView(dataGrid_Budget.Items[index]);
row = (DataGridRow)dataGrid_Budget.ItemContainerGenerator.ContainerFromIndex(index);
}
return row;
}
public static T GetVisualChild<T>(Visual parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null)
{
child = GetVisualChild<T>(v);
}
if (child != null)
{
break;
}
}
return child;
}
Your SQL syntax has to be corrected like,
SqlCommand update_comm = new SqlCommand();
update_comm.Connection = Conn;
update_comm.CommandText = "UPDATE Budget SET id= #u_id, Name= #u_name WHERE person= #psn";
var update_da = new SqlDataAdapter(update_comm);
update_da.SelectCommand.Parameters.Add(new SqlParameter("#u_id", SqlDbType.Int));
update_da.SelectCommand.Parameters["#u_id"].Value = yourintvalue;
update_da.SelectCommand.Parameters.Add(new SqlParameter("#u_name", SqlDbType.NVarChar));
update_da.SelectCommand.Parameters["#u_name"].Value = yourstringvalue;
update_da.SelectCommand.Parameters.Add(new SqlParameter("#psn", SqlDbType.NVarChar));
update_da.SelectCommand.Parameters["#psn"].Value = yourstringvalue;
var update_ds = new DataSet();
update_da.Fill(update_ds);
'UPDATE' should be used with 'SET' together.
And if you want to update the actual SQL database with the value of edited rows of DataGrid, please try this.
da.UpdateCommand = new SqlCommandBuilder(da).GetUpdateCommand();
da.Update(griddt);
SqlConnection uniConn = null;
SqlCommand cmd = null;
SqlDataAdapter sda = null;
DataTable dt = new DataTable();
uniConn = new SqlConnection(
"server=localhost;" + "Trusted_Connection=yes;" +
"database=Production; " + "connection timeout=30");
cmd = new SqlCommand("UPDATE Budget(id, Name, Quantity, Rate, Time)",
uniConn);
uniConn.Open();
sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
BudgetGrid.ItemsSource = dt.DefaultView;
uniConn.Close();
Did you forget to close the connection?
I'm doing an application where there will be two filters.
First filter is when user will enter an ID then only the data of that ID is displayed. I've managed to done that but the problem is on the second filter I try to implement. After the user enter the ID then display the ID data, then the user can filter that data even more based dates. So I try using datetimepicker tools.
But when I choose the date, mydatagridview won't filter to show only the chosen date data. It still shows all the data from the first ID filter.
Any help will greatly appreciated.
Here is my code :
private void trackBtn_Click(object sender, EventArgs e)
{
dataGridView1.Visible = true;
if (dataGridView1.Visible == true)
{
webBrowser1.Location = new Point(12, 397);
}
//DataTable dt = null;
string connoInput = textBox1.Text;
string conString = Properties.Settings.Default.BMSDATAConnectionString;
using (SqlCeConnection con = new SqlCeConnection(#"Data Source=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2008\Projects\TrackCon\TrackCon\BMSDATA.sdf;Persist Security Info = True;Password=Gdex123$"))
{
string Ids = "conno= '" + System.Text.RegularExpressions.Regex.Replace(textBox1.Text.Trim(), #"\s*\n\s*", "' OR conno= '") + "'";
SqlCeCommand com = new SqlCeCommand("SELECT conno,cmpsno,ctrx,dsysdate,cstnno,corigin FROM BRDATA WHERE " +Ids, con);
SqlCeDataAdapter adap = new SqlCeDataAdapter(com);
DataSet set = new DataSet();
adap.Fill(set);
if (set.Tables.Count > 0)
{
bRDATABindingSource1.DataSource = set.Tables[0];
}
dataGridView1.DataSource = bRDATABindingSource1;
con.Close();
}
}
private void trackMPSbtn_Click(object sender, EventArgs e)
{
dataGridView1.Visible = true;
if (dataGridView1.Visible == true)
{
webBrowser1.Location = new Point(12, 397);
}
//DataTable dt = null;
//string connoInput = textBox1.Text;
string conString = Properties.Settings.Default.BMSDATAConnectionString;
using (SqlCeConnection con = new SqlCeConnection(#"Data Source=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2008\Projects\TrackCon\TrackCon\BMSDATA.sdf;Persist Security Info = True;Password=Gdex123$"))
{
dataGridView1.DataSource = bRDATABindingSource1;
string Ids = "cmpsno= '" + System.Text.RegularExpressions.Regex.Replace(textBox2.Text.Trim(), #"\s*\n\s*", "' OR cmpsno= '") + "'";
con.Open();
SqlCeCommand com = new SqlCeCommand("SELECT conno,cmpsno,ctrx,dsysdate,cstnno,corigin FROM BRDATA WHERE " + Ids, con);
SqlCeDataAdapter adap = new SqlCeDataAdapter(com);
DataSet set = new DataSet();
adap.Fill(set);
if (set.Tables.Count > 0)
{
bRDATABindingSource1.DataSource = set.Tables[0];
}
dataGridView1.DataSource = bRDATABindingSource1;
con.Close();
}
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
bRDATABindingSource1.Filter = string.Format("dsysdate = #{0}#", dateTimePicker1.Value.ToLongDateString());
}
}
}
EDITED
I'm afraid the DataSource of dataGridView1 is local variable dt in both your events. But you're likely trying to filter an instance field bRDATABindingSource1. There is no more context information for me. Are you sure this is correct?
Try to use bRDATABindingSource1 instead of dt, and see if that works.