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;
}
Related
As you can read from header, i had a problem with insert from datagridview. Here code of my shiny probram:
namespace LibrarianApp
{
public partial class Start : Form
{
public Start()
{
InitializeComponent();
Start_Load();
}
private static DataTable GetData(string SQLiteCommand)
{
string conString = "Data Source=Books.db;Version=3;";
SQLiteConnection cnn = new SQLiteConnection(conString);
SQLiteCommand command = new SQLiteCommand(SQLiteCommand, cnn);
SQLiteDataAdapter adapter = new SQLiteDataAdapter();
adapter.SelectCommand = command;
DataTable table = new DataTable();
adapter.Fill(table);
return table;
}
private void Start_Load()
{
dataGridView1.DataSource = GetData("select * from Books where BookName like '%" + NameTextBox.Text + "%' and AuthorName like '%" + AuthorTextBox.Text + "%' and Genre like '%" + GenreTextBox.Text + "%'");
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders;
dataGridView1.BorderStyle = BorderStyle.Fixed3D;
dataGridView1.AllowUserToAddRows = false;
dataGridView1.Columns["ID"].Visible = false; dataGridView1.Columns["BookName"].HeaderText = "Название"; dataGridView1.Columns["AuthorName"].HeaderText = "Автор";
dataGridView1.Columns["Genre"].HeaderText = "Жанр"; dataGridView1.Columns["Amount"].HeaderText = "Количество в наличии";
}
private void SearchButtom_Click(object sender, EventArgs e)
{
Start_Load();
}
private void AddBookButtom_Click(object sender, EventArgs e)
{
AddBookForm AddDialog = new AddBookForm();
AddDialog.Show();
}
private void RefreshButtom_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = GetData("select * from Books");
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders;
dataGridView1.BorderStyle = BorderStyle.Fixed3D;
dataGridView1.AllowUserToAddRows = false;
dataGridView1.Columns["ID"].Visible = false; dataGridView1.Columns["BookName"].HeaderText = "Название"; dataGridView1.Columns["AuthorName"].HeaderText = "Автор";
dataGridView1.Columns["Genre"].HeaderText = "Жанр"; dataGridView1.Columns["Amount"].HeaderText = "Количество в наличии";
}
private void InsertFromGridButtom_Click(object sender, EventArgs e)
{
string StrQuery;
try
{
string conString = "Data Source=Books.db;Version=3;";
using (SQLiteConnection conn = new SQLiteConnection(conString))
{
using (SQLiteCommand comm = new SQLiteCommand())
{
comm.Connection = conn;
conn.Open();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
StrQuery = #"INSERT INTO tableName VALUES ("
+ dataGridView1.Rows[i].Cells["ColumnName"].Text + ", "
+ dataGridView1.Rows[i].Cells["ColumnName"].Text + ");";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
}
catch
{
}
}
}
}
As you can see i use datagridview datasourse straight from the .db file. And i think, that why i got that error: "DataGridViewCell" does not contain definition for 'Text'"
https://ibb.co/1M4YkZX
How can i fix this?
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]))
{
...
}
I have this code in my btnLogin in Form1 to get data from MS Access database and I want it to display in Form2using label but I don't know how to pass it to Form2
private void btnLogin_Click(object sender, EventArgs e)
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
if ((this.txtUser.Text == "admin") && (this.txtPass.Text == "admin"))
{
Form1 main = new Form1();
main.txtHere.Text = txtUser.Text;
main.Show();
this.Hide();
}
else {
command.CommandText = "select * from StudentsTBL where LastName='" + txtUser.Text + "' and FirstName='" + txtPass.Text + "'";
OleDbDataReader reader = command.ExecuteReader();
int count = 0;
while (reader.Read()) {
count = count + 1;
//count++;
}
if (count == 1) {
MessageBox.Show("Login Successful!");
List<String> stdNo = new List<String>();
List<String> middleName = new List<String>();
List<String> section = new List<String>();
List<String> year = new List<String>();
List<String> sem = new List<String>();
List<String> address = new List<String>();
List<String> dob = new List<String>();
List<String> gender = new List<String>();
List<String> age = new List<String>();
List<String> contact = new List<String>();
List<String> desc = new List<String>();
command = new OleDbCommand("select * from StudentsTBL", connection);
reader = command.ExecuteReader();
while (reader.Read())
{
stdNo.Add(reader["StudentNo"].ToString());
middleName.Add(reader["Middle"].ToString());
section.Add(reader["stdSection"].ToString());
year.Add(reader["stdYear"].ToString());
sem.Add(reader["stdSem"].ToString());
address.Add(reader["stdAddress"].ToString());
dob.Add(reader["stdDob"].ToString());
gender.Add(reader["stdGender"].ToString());
age.Add(reader["stdAge"].ToString());
contact.Add(reader["ContactNo"].ToString());
desc.Add(reader["stdDesc"].ToString());
}
StudentProfile stdProfile = new StudentProfile(txtUser.Text, txtPass.Text);
stdProfile.Show();
this.Hide();
}
else if (count > 1)
{
MessageBox.Show("Duplicate username and password!!");
}
else {
MessageBox.Show("Login Failed!");
}
}
connection.Close();
}
source: Getting data from MS Access database and display it in a listbox
Why you are not using structures ?
It will make your like easy yo can handle a lot of information in a single
variable.
And why you not make a global variable ?
It will be available from any part of you application.
I have project like this on GitHub you can downloaded as example reference
structure UserInfo{
public string stdNo;
public string middleName;
public string section;
public string year;
public string sem;
public string address;
public string dob;
public string gender;
public string age;
public string contact;
public string desc;
}
//===>Define a global variable to handle
public static UserInfo LoggedUsrInfo = new UserInfo();
private void btnLogin_Click(object sender, EventArgs e)
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
if ((this.txtUser.Text == "admin") && (this.txtPass.Text == "admin"))
{
Form1 main = new Form1();
main.txtHere.Text = txtUser.Text;
main.Show();
this.Hide();
}
else {
command.CommandText = "select * from StudentsTBL where LastName='" + txtUser.Text + "' and FirstName='" + txtPass.Text + "'";
DataTable Tbl = new DataTable();
OleDbDataReader reader = command.ExecuteReader();
Tbl.Load(reader,LoadOption.OverwriteChanges);//===>Retrieve data and load to datatble
reader.Close();//Close the reader
if (Tbl.Rows.Count > 0) {//Count if the data table retrieve some info
DataTable TblInfo = new DataTable();
MessageBox.Show("Login Successful!");
command = new OleDbCommand("select * from StudentsTBL", connection);
reader = command.ExecuteReader();
TblInfo.Load(reader,LoadOption.OverwriteChanges);
reader.Close();//Close the reader
LoggedUsrInfo.stdNo = TblInfo.Rows[0]["StudentNo"].ToString();
LoggedUsrInfo.middleName = TblInfo.Rows[0]["Middle"].ToString();
LoggedUsrInfo.section = TblInfo.Rows[0]["stdSection"].ToString();
LoggedUsrInfo.year = TblInfo.Rows[0]["stdYear"].ToString();
LoggedUsrInfo.sem =TblInfo.Rows[0]["stdSem"].ToString();
LoggedUsrInfo.address = TblInfo.Rows[0]["stdAddress"].ToString();
LoggedUsrInfo.dob = TblInfo.Rows[0]["stdDob"].ToString();
LoggedUsrInfo.gender = TblInfo.Rows[0]["stdGender"].ToString();
LoggedUsrInfo.age = TblInfo.Rows[0]["stdAge"].ToString();
LoggedUsrInfo.contact = TblInfo.Rows[0]["ContactNo"].ToString();
LoggedUsrInfo.desc = TblInfo.Rows[0]["stdDesc"].ToString();
StudentProfile stdProfile = new StudentProfile(txtUser.Text, txtPass.Text);
stdProfile.Show();
this.Hide();
}
else if (count > 1)
{
MessageBox.Show("Duplicate username and password!!");
}
else {
MessageBox.Show("Login Failed!");
}
}
connection.Close();
}
/*
you can access to UserInfo calling in this way from your Form2
Load Event
Label1.Text = Form1.LoggedUsrInfo.middleName;
*/
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.
I would like to edit my database record from datagridview and save from there. What properties do i need to declare to enable me to edit the datagrid? And button2 is my save button, how do i update to the database? Someone please help me thanks!
{
//Get ID
string strTagIds = string.Empty;
//Connection to datebase
string c1 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Project.mdb";
OleDbConnection con = new OleDbConnection(c1);
}
private void button1_Click(object sender, EventArgs e)
{
//button1.Click += new EventHandler(dataGridView1_CellContentClick);
//Bind button
string txt = textBox1.Text;
string strOleDbConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Project.mdb";
string strSqlStatement = string.Empty;
strSqlStatement = "SELECT * FROM jiahe WHERE [User] = '" + txt + "'";
OleDbConnection objConnection = new OleDbConnection(strOleDbConnectionString);
OleDbDataAdapter objAdapter = new OleDbDataAdapter(strSqlStatement, objConnection);
DataSet ds = new DataSet();
objAdapter.Fill(ds);
DataTable dt = ds.Tables[0];
dataGridView1.DataSource = dt.DefaultView;
try
{
if (dt.Rows.Count == 1)
{
string strLine = string.Empty;
string strUser = string.Empty;
foreach (DataRow dr in dt.Rows)
{
string strTags = dr["Tag ID"].ToString();
strUser = dr["User"].ToString();
string strAge = dr["Age"].ToString();
string strPhoneNumber = dr["Phone Number"].ToString();
// prepare command string
string selectString = #"SELECT Status FROM jiahe where [User] = '" + textBox1.Text + "'";
// 1. Instantiate a new command with command text only
OleDbCommand cmd = new OleDbCommand(selectString, objConnection);
// 2. Set the Connection property
cmd.Connection.Open();
// 3. Call ExecuteScalar to send command
string str = cmd.ExecuteScalar().ToString();
cmd.Connection.Close();
}
}
else
{
if (dt.Rows.Count == 0)
{
MessageBox.Show("Invalid input!");
}
}
}
catch (Exception)
{
MessageBox.Show("Error!");
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, EventArgs e)
{
//dataGridView1.BeginEdit(true);
//MessageBox.Show("Hello");
}
private void button2_Click(object sender, EventArgs e)
{
}
You need datagridview cell content value changed. You should make a string which will be updated each time you edit a row with the ID/index of the selected row. Then you can make an update to the database when the button2 is clicked.