I have the main form Form1 which opens when I run the app. I pass a list from this form which contains Supplier objects to a secondary Form2, to help me build Product objects using an attribute of objects stored in the Suppliers list in Form1.
In Form2 I have the list of Product objects which I want to pass back to Form1 after i complete it and show it in a ListView. But something is not working..i don't figure out what. Thank you in advance.
Form1:
public partial class Form1 : Form
{
public ArrayList suplist = new ArrayList(); //suppliers list
public List<Product> productlist = new List<Product>(); //products list which will be populated with objects sent from Form2
public Form1()
{
InitializeComponent();
//Read Suppliers from txt
StreamReader sr = new StreamReader("Suppliers.txt");
string linie = null;
while((linie=sr.ReadLine())!=null) {
try
{
int id = Convert.ToInt32(linie.Trim().Split(',')[0]);
string nume = linie.Trim().Split(',')[1];
Supplier sp = new Supplier(id, nume);
suplist.Add(sp);
}
catch(Exception ex) { MessageBox.Show(ex.Message); }
}
listView1.Columns.Add("ID");
listView1.Columns.Add("Nume");
listView1.Columns.Add("Units");
listView1.Columns.Add("Price");
listView1.Columns.Add("SUpplier Id");
}
private void button1_Click(object sender, EventArgs e)
{
Form2 from = new Form2(suplist);
from.ShowDialog();
}
public List<Product> ProductList
{
get { return productlist; }
set { productlist = value; }
}
private void button2_Click(object sender, EventArgs e)
{ //this function is supposed to populate listview with the productlist objects when i click the button;
//not sure if it is wrong writeed, or passing the list of products created in Form2 failed
foreach (Product p in productlist)
{
//listView1.Items.Add(p.Id);
ListViewItem itm = new ListViewItem(p.Id.ToString());
itm.SubItems.Add(p.Nume);
itm.SubItems.Add(p.Units.ToString());
itm.SubItems.Add(p.Price.ToString());
itm.SubItems.Add(p.SupplierId.ToString());
}
}
}
Form2:
public partial class Form2 : Form
{
public List<Product> prodList = new List<Product>(); //list which stores the Products == > the list i want to send back to Form 1
public ArrayList supplierList = new ArrayList(); //list of suppliers received from From 1, used to build Products objects
public Form2(ArrayList suplist)
{
InitializeComponent();
supplierList = suplist;
foreach(Supplier s in supplierList)
{
comboBox1_supID.Items.Add(s.Id);
}
Product p1 = new Product(1, "Cola", 4, 45, 1);
Product p2 = new Product(2, "Fanta", 32, 22, 2);
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1__id.Text == "") errorProvider1.SetError(textBox1__id, "Introduceti id");
else if (textBox2_nume.Text == "") errorProvider1.SetError(textBox2_nume, "Introduceti numele");
else if (textBox3_units.Text == "") errorProvider1.SetError(textBox3_units, "Introduceti units");
else if (textBox4_price.Text == "") errorProvider1.SetError(textBox4_price, "enter price");
else if (comboBox1_supID.Text == "") errorProvider1.SetError(comboBox1_supID, "Select sup id");
else
try
{
int id = Convert.ToInt32(textBox1__id.Text);
string nume = textBox2_nume.Text;
int units = Convert.ToInt32(textBox3_units.Text);
double price = Convert.ToDouble(textBox4_price.Text);
int supid = Convert.ToInt32(comboBox1_supID.Text);
Product pd = new Product(id, nume, units, price, supid);
prodList.Add(pd);
MessageBox.Show("Produs adaugat cu succes");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
textBox1__id.Clear();
textBox2_nume.Clear();
textBox4_price.Clear();
textBox3_units.Clear();
errorProvider1.Clear();
}
}
private void textBox4_price_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar))
{
errorProvider1.SetError(textBox4_price, "Introduceti numai cifre");
}
else errorProvider1.Clear();
}
private void button2_Click(object sender, EventArgs e)
{
Form1 frm = new Form1();
frm.productlist = prodList;
frm.Show();
}
}
I want to send to Form1 prodList from Form2, (store it in productlist i guess in Form1) and show them in listview1 in Form1.
On short, in Form1 I create Suppliers, store them in suplist and pass this list to Form2(in supplierlist). In Form2 I create Products, store them in prodList and pass it to Form1(in productList). Why isn't working? and why listview doesn't show anything??
I haven't worked yet with the ListView-Object itself yet but I think you missed to add the created ListViewItem to your ListView
foreach (Product p in productList)
{
ListViewItem itm = new ListViewItem(p.Id.ToString());
itm.SubItems.Add(p.Nume);
itm.SubItems.Add(p.Units.ToString());
itm.SubItems.Add(p.Price.ToString());
itm.SubItems.Add(p.SupplierId.ToString());
listView1.Items.Add(itm);
}
I am trying to develop a restaurant billing application in windows form.
so I created dynamic buttons.
now I need a table which will retrieve data from database for each button click.
How can it possible?
private void newb_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
// textBox1.Text = btn.Text;
connection con = new connection();
con.connecting();
// Button b = new Button();
int i = 0;
var query = "select itemname,itemcode,price from item_master where itemcode =" + btn.Name;
MySqlCommand cmd = new MySqlCommand(query, con.con);
while (i < 10)
{
MySqlDataAdapter sda = new MySqlDataAdapter();
DataTable dt = new DataTable();
sda.SelectCommand = cmd;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bsource = new BindingSource();
bsource.DataSource = dbdataset;
dataGridView1.DataSource = bsource;
// MessageBox.Show(btn.Name);
i++;
}
// sda.Update(dbdataset);
// =dataGridView1.Rows[0]
//// MySqlDataReader mdr;
//// mdr = cmd.ExecuteReader();
// while (mdr.Read())
// {
//// textBox1.Text = (mdr["itemname"].ToString());
// }
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
I am trying to pass database value into a another from using visual studio windows form. How do I access the data outside the while loop? and save to a string and pass that value into form2. I keep getting this error when passing to form2: Additional information: Syntax error (missing operator) in query expression 'pin='
my code for form1:
namespace ATM
{
public partial class Form1 : Form
{
String conn_string = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Dro\\Desktop\\ATM\\Database11.accdb; Persist Security Info=False;";
OleDbConnection conn = null;
public int pinnumber = 3300;
public string dbpin;
public string oppin;
public Form1()
{
InitializeComponent();
}
private void button13_Click(object sender, EventArgs e)
{
runQuery();
//checks PIN is entered or not
if (textBox2.Text.Length == 0)
{
textBox2.Text = textBox2.Text + "----";
}
else if (dbpin == textBox2.Text)//checks whether pin is correct and then shows the form 2(menu)
{
Form2 menu = new Form2();
menu.Show();
this.Hide();
}
else
{
textBox1.Text = "The PIN is Incorrect! Try Again!";
}
}
private void button_click(object sender, EventArgs e)
{
if (textBox2.Text == "----")
{
textBox2.Clear();
textBox1.Clear();
}
if (textBox2.Text.Length < 4)
{
Button button = (Button)sender;
textBox2.Text = textBox2.Text + button.Text;
textBox2.PasswordChar = '*';
}
}
private void button12_Click(object sender, EventArgs e)
{
textBox2.Clear();
}
private void runQuery()
{
conn = new OleDbConnection(conn_string);
MessageBox.Show("successfully connected");
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM atmDB where pin="+textBox2.Text;
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
dbpin = dr["PIN"].ToString();
}
MessageBox.Show(dbpin);
}
}
}
I have a datagridview with BindingSource to Linq to SQL as datasource. When I try to insert or delete the data, the gridview is not refreshed.
SampleDataContext context = new SampleDataContext();
BindingSource bindingSource = new BindingSource();
public Form1()
{
InitializeComponent();
bindingSource.DataSource = context.Persons;
PersonGridView.DataSource = bindingSource;
}
private void AddButton_Click(object sender, EventArgs e)
{
context.Persons.InsertOnSubmit(new Person { Name = , Address = });
context.SubmitChanges();
}
private void DeleteButton_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in PersonGridView.SelectedRows)
{
var person = context.Persons.FirstOrDefault(x => x.ID == int.Parse(row.Cells[0].Value.ToString()));
context.Persons.DeleteOnSubmit(person);
}
context.SubmitChanges();
}
Am I missing something here ?
Best Regards,
Brian
Viola after try many solutions I Have a better solution just change insert and delete operation to bindingsource
SampleDataContext context = new SampleDataContext();
BindingSource bindingSource = new BindingSource();
public Form1()
{
InitializeComponent();
bindingSource.DataSource = context.Persons;
PersonGridView.DataSource = bindingSource;
}
private void AddButton_Click(object sender, EventArgs e)
{
bindingSource.Add(new Person { Name = "Hello", Address = "Hahahaha123" });
context.SubmitChanges();
}
private void DeleteButton_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in PersonGridView.SelectedRows)
{
var person = context.Persons.FirstOrDefault(x => x.ID == int.Parse(row.Cells[0].Value.ToString()));
bindingSource.Remove(person);
}
context.SubmitChanges();
}
my error is simple but for me it is hard to fix it because my knowledge is not good . which is when i Enter the record by clicking the Addbutton of AddStudent record then the record that i deleted like record StudentID = 1, FirstName =Raju ,LastName=Abbasi
After Delete it again and press save Change even After that when i again try to use the ID=1 means enter the Record with ID=1 that i have been deleted and record the StudentID=1 ,FirstName =Ram ,LastName=Rakish .Then error is occur which is
private static SqlDataAdapter CreateSutdentDataAdapter()
{
string gettSQL = "SELECT * FROM Student";
string insertSQL = "SET IDENTITY_INSERT Student ON;INSERT INTO Student(StudentID, FirstName,LastName,Gender,GPA,MyImage)" +
"VALUES (#StudentID,#FirstName,#LastName,#Gender,#GPA,#MyImage);SET IDENTITY_INSERT Student OFF";
string updateSQL = "UPDATE Student SET FirstName=#FirstName,LastName=#LastName ,Gender=#Gender, MyImage=#MyImage," +
" GPA=#GPA WHERE StudentID=#StudentID";
string deleteSQL = "DELETE FROM Student WHERE StudentID=#StudentID";
SqlDataAdapter dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = new SqlCommand(gettSQL, ConnectionManager.GetConnection());
dataAdapter.InsertCommand = new SqlCommand(insertSQL, ConnectionManager.GetConnection());
dataAdapter.InsertCommand.Parameters.Add("#StudentID", SqlDbType.Int).SourceColumn = "StudentID";
dataAdapter.InsertCommand.Parameters.Add("#FirstName", SqlDbType.VarChar,25 ).SourceColumn = "FirstName";
dataAdapter.InsertCommand.Parameters.Add("#LastName", SqlDbType.VarChar, 25 ).SourceColumn = "LastName";
dataAdapter.InsertCommand.Parameters.Add("#Gender", SqlDbType.VarChar ,1).SourceColumn = "Gender";
dataAdapter.InsertCommand.Parameters.Add("#GPA", SqlDbType.Float ).SourceColumn = "GPA";
dataAdapter.InsertCommand.Parameters.Add("#MyImage", SqlDbType.VarBinary).SourceColumn = "MyImage";
dataAdapter.UpdateCommand = new SqlCommand(updateSQL, ConnectionManager.GetConnection());
dataAdapter.UpdateCommand.Parameters.Add("#StudentID", SqlDbType.Int).SourceColumn = "StudentID";
dataAdapter.UpdateCommand.Parameters.Add("#FirstName", SqlDbType.VarChar,25 ).SourceColumn = "FirstName";
dataAdapter.UpdateCommand.Parameters.Add("#LastName", SqlDbType.VarChar, 25 ).SourceColumn = "LastName";
dataAdapter.UpdateCommand.Parameters.Add("#Gender", SqlDbType.VarChar ,1).SourceColumn = "Gender";
dataAdapter.UpdateCommand.Parameters.Add("#GPA", SqlDbType.Float ).SourceColumn = "GPA";
dataAdapter.UpdateCommand.Parameters.Add("#MyImage", SqlDbType.VarBinary).SourceColumn = "MyImage";
dataAdapter.DeleteCommand = new SqlCommand(deleteSQL, ConnectionManager.GetConnection());
dataAdapter.DeleteCommand.Parameters.Add("#StudentID", SqlDbType.Int).SourceColumn = "StudentID";
return dataAdapter;
}
private static void DefinestudentTableSchema(DataTable table)
{
DataColumn StudentIDColumn = table.Columns.Add("StudentID", typeof(string));
StudentIDColumn.AllowDBNull = false;
table.PrimaryKey = new DataColumn[] { StudentIDColumn };
DataColumn StudentFirstName = table.Columns.Add("FirstName", typeof(string));
StudentFirstName.MaxLength = 150;
DataColumn StudentLastName = table.Columns.Add("LastName", typeof(string));
StudentLastName.MaxLength = 150;
DataColumn StudentGender = table.Columns.Add("Gender", typeof(string ));
DataColumn StudentGPA = table.Columns.Add("GPA", typeof(string ));
DataColumn StudentImage = table.Columns.Add("MyImage", typeof(Byte[]));
}
private static DataSet CreateStudentTrackerDataSet()
{
DataSet StudentTrackerDataSet = new DataSet();
DataTable StudentTable = StudentTrackerDataSet.Tables.Add("Student");
DefinestudentTableSchema(StudentTable);
return StudentTrackerDataSet;
}
public static DataSet GetData()
{
DataSet StudentTrakerDataSet = CreateStudentTrackerDataSet();
StudentTrakerDataSet.EnforceConstraints = false;
StudentDataAdapter.Fill(StudentTrakerDataSet.Tables["Student"]);
StudentTrakerDataSet.EnforceConstraints = true;
return StudentTrakerDataSet;
}
public AddModifyStudentRecords(DataSet ds, DataRow row)
{
public static void SaveData(ref DataSet changesDataSet)
{
DataSet addedDataSet = changesDataSet.GetChanges(DataRowState.Added);
if (addedDataSet != null)
{
StudentDataAdapter.Update(addedDataSet.Tables["Student"]);
changesDataSet.Merge(addedDataSet); // Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints
}
DataSet modifiedDataSet = changesDataSet.GetChanges(DataRowState.Modified);
if (modifiedDataSet != null)
{
StudentDataAdapter.Update(modifiedDataSet.Tables["Student"]);
changesDataSet.Merge(modifiedDataSet);
}
DataSet deletedDataSet = changesDataSet.GetChanges(DataRowState.Deleted);
if (deletedDataSet != null)
{
StudentDataAdapter.Update(deletedDataSet.Tables["Student"]);
deletedDataSet.Merge(deletedDataSet);
}
here is my Addmodifyform logic for add the StudentID
public partial class AddModifyStudentRecords : Form
{
DataSet StudentTrackerDataSet;
DataRow currentRow;
public AddModifyStudentRecords()
{
InitializeComponent();
}
public AddModifyStudentRecords(DataSet ds)
{
InitializeComponent();
StudentTrackerDataSet = ds;
currentRow = null;
}
public AddModifyStudentRecords(DataSet ds, DataRow row)
{
InitializeComponent();
StudentTrackerDataSet = ds;
currentRow = row;
textBox1.Text =currentRow["StudentID"] .ToString();
textBox2.Text = currentRow["FirstName"].ToString();
textBox4.Text = currentRow["LastName"].ToString();
textBox3.Text = currentRow["Gender"].ToString();
textBox5.Text = currentRow["GPA"].ToString();
txtBrowseFile.Text = currentRow["MyImage"].ToString ();
byte[] data = (byte[])currentRow ["MyImage"];
MemoryStream ms = new MemoryStream(data);
pictureBox1.Image = Image.FromStream(ms);
string StudentID = textBox1.Text.ToString();
string StudentFirstName = textBox2.Text.ToString();
string StudentLastName = textBox4.Text.ToString();
string Gender = textBox3.Text.ToString();
string GPA = textBox5.Text.ToString();
Image MyImage = pictureBox1.Image;
DataTable table = StudentTrackerDataSet.Tables["Student"];
if (currentRow == null) {
currentRow = table.NewRow();
currentRow["StudentID"] = textBox1.Text.ToString();
table.Rows.Add(currentRow );
}
currentRow .BeginEdit();
currentRow ["StudentID" ]=StudentID ;
currentRow["FirstName"] = StudentFirstName;
currentRow["LastName"] = StudentLastName;
currentRow["Gender"] = Gender;
currentRow["GPA"] = GPA;
currentRow["MyImage"] = convertToByte(txtBrowseFile.Text);
currentRow.EndEdit();
Close();
}
public partial class AditStudent : Form
{
// Creat the Class variabl Dataset to track the Student
private DataSet StudentTrackerDataset;
public AditStudent()
{
InitializeComponent();
dataGridView1.DataError += DataGridView1_DataError;
StudentTrackerDataset = ProjectOfSchool.DataAccessLayer.DAC.GetData();
DataTable StudentTable = StudentTrackerDataset.Tables["Student"];
dataGridView1.DataSource = StudentTable;
//StudentTable.Columns["ID"].AutoIncrement = true;
for (int i = 0; i < dataGridView1.Columns.Count; i++)
if (dataGridView1.Columns[i] is DataGridViewImageColumn)
{
((DataGridViewImageColumn)dataGridView1.Columns[i]).ImageLayout = DataGridViewImageCellLayout.Stretch;
break;
}
}
private void DataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
string message = string.Format("Error in {0} columan in row {1}:{2}", e.ColumnIndex, e.RowIndex, e.Exception.Message);
MessageBox.Show(message, "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
private void button1_Click(object sender, EventArgs e)
{
AddModifyStudentRecords AddStudent = new AddModifyStudentRecords(StudentTrackerDataset);
AddStudent.ShowDialog();
}
private void button2_Click(object sender, EventArgs e)
{
object id = dataGridView1.CurrentRow.Cells["StudentID"].Value;
DataRow StudentRow = StudentTrackerDataset.Tables["Student"].Rows.Find(id);
AddModifyStudentRecords modifyStudent = new AddModifyStudentRecords(StudentTrackerDataset, StudentRow);
modifyStudent.ShowDialog();
}
private void button3_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("Are you sure", "Delete Current Row", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
object id = dataGridView1.CurrentRow.Cells["StudentID"].Value;
DataRow currentRow = StudentTrackerDataset.Tables["Student"].Rows.Find(id);
currentRow.Delete();
}
}
private void button4_Click(object sender, EventArgs e)
{
if (!StudentTrackerDataset.HasChanges())
{
MessageBox.Show("There are no Change to Save ", "Save Changes", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
try
{
DataSet changesDateSet = StudentTrackerDataset.GetChanges();
ProjectOfSchool.DataAccessLayer.DAC.SaveData(ref changesDateSet);
StudentTrackerDataset.Merge(DAC.GetData());
MessageBox.Show("Data Save Successfully.", "Save Changes");
}
catch (SqlException ex)
{
MessageBox.Show("Data Not Saved:" + ex.Message, "Save Changes", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
private void button5_Click(object sender, EventArgs e)
{
if (!StudentTrackerDataset.HasChanges())
{
MessageBox.Show("There are no Changes to Save.", "Save Changes", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
DialogResult result = MessageBox .Show ("Are you Sure?","Reject Changes", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes )
{
StudentTrackerDataset.RejectChanges();
}
}
}
And When i terminate the program and re execute the program then i saw that StudntID=1 is also save to Database with ID=1
or When i Delete the StudentID =1 and press save Change after press save Change when i also Terminate the program and re exicute the program and after that when i Enter the StudentID =1 Then no error is occur
And other way without termination is to Delete the record StudentID1 but when you Add the Student record but not Add the StudentID=1 But add the StudentID other then 1 in this case error is also not happend . Dear Sherik I have been solve my other error but i have still error which is in my Tittle So please responding me for this error And i re edited my code also So please replay me Thanks
I have record in my Database which have following Datatype as
StudentID=INT,
FirstName=VarChar,
LastName=VarChar,
Gender=Varchar,
GPA=Float,
MyImage=Vabinary (MAX)
Or may be Datarow fail to Delete the record or Update the record. I don't know please tell me and thanks to reply me and I am waiting for your reply.
The error message seems to indicate that you are hitting a Primary Key constraint.
I would suggest that you first stop allowing the user to enter the Student ID field. Let it be generated as an auto increment key in whatever database you are using. In Access, it is called AutoNumber.
Once you have done that, re test and post the results.