Hi I have a Table 'Suppliers' and another 'SupplierPlants' I have both tables bound to DataGridViews via code:
bsSuppliers = new BindingSource();
bsSuppliers.DataSource = AppData.Suppliers;
bsSuppliers.AllowNew = true;
dgvSuppliers.DataSource = bsSuppliers;
dgvSuppliers.Refresh();
bsSuppliersPlants = new BindingSource();
bsSuppliersPlants.DataSource = AppData.SupplierPlants;
bsSuppliersPlants.AllowNew = true;
dgvSupplierPlants.DataSource = bsSuppliersPlants;
dgvSupplierPlants.Refresh();
The AppData class holds all of my DB entities:
Db = new PureTrialEntities();
Db.Suppliers.Load();
Suppliers = Db.Suppliers.Local;
Db.SupplierPlants.Load();
SupplierPlants = Db.SupplierPlants.Local;
Now I have RowEnter event bound for the Supplier DataGridView so that it will only show Plants for the selected Suppliers:
private void dgvSuppliers_RowEnter(object sender, DataGridViewCellEventArgs e)
{
var supplier = ((Supplier)dgvSuppliers.Rows[e.RowIndex].DataBoundItem);
if (supplier == null)
return;
ShowSupplierPlants(supplier.SupplierID);
}
private void ShowSupplierPlants(int supplierID)
{
var plantData = AppData.SupplierPlants.Where(x => x.SupplierID == supplierID); //Get selected Suppliers Plant Data.
if (plantData.Any())
bsSuppliersPlants.DataSource = plantData;
else
bsSuppliersPlants.DataSource = new List<SupplierPlant>();
dgvSupplierPlants.Refresh();
}
The issue is when I call AppData.Db.SaveChanges(); it will correctly apply all changes to the Suppliers Table but it wont Add new rows for the SupplierPlants table as I have taken a subset of the local db.
Do I have to manually manage new rows added for this Table as I am using a subset and not the whole Local db?
You should insert them manually,
Db.SupplierPlants.Add(item);
Detailed information
Hope helps,
just as a FYI i bound the DGV CellEndEdit and just added the newly added line to the context like so:
private void dgvSupplierPlants_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
var data = ((SupplierPlant)((DataGridView)sender).Rows[e.RowIndex].DataBoundItem); //Get the Data for the edited Row.
if (AppData.Db.Entry(data).State == EntityState.Detached)
{
AppData.SupplierPlants.Add(data);
}
}
Related
I have been doing this schedule system and I want to populate data inside this datagrid view where my users can select a particular value I previously saved in database and display it here to arrange data and then print...
so far I was unable to populate data inside the database. Can you guys give me a code to do this
this is my form
this is my database
You need to use DataSource. Please check the link Steps To Add Combobox Inside Datagridview or code below.
private void dgv_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex > -1)
{
DataGridViewComboBoxCell l_objGridDropbox = new DataGridViewComboBoxCell();
if (dgv.Columns[e.ColumnIndex].Name.Contains("Info"))
{
dgv[e.ColumnIndex, e.RowIndex] = l_objGridDropbox;
l_objGridDropbox.DataSource = GetMyData();
l_objGridDropbox.ValueMember = "Info";
l_objGridDropbox.DisplayMember = "Info";
}
}
}
private DataTable GetMyData()
{
DataTable lInfo = new DataTable();
lInfo.Columns.Add("Info", typeof(string));
lInfo.Rows.Add("A");
lInfo.Rows.Add("B");
lInfo.Rows.Add("C");
return lInfo ;
}
I am doing Entity Framework and I have a database where there is no connection between the two tables. My form has two datagridviews each showing the contents of those tables on load. I also have two buttons. When I select any cell (which selects the entire row) on the sport table and click copy, it moves the data to the health table and removes it from the sport one. The second button does vice versa. What do you think is wrong?
I have tried delete and add and there seems to be a validation error. How can I fix this?
public partial class Form1 : Form
{
SportsAreUsEntities mySports = new SportsAreUsEntities();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
RefreshGrids();
}
private void RefreshGrids()
{
var allSport = from eachSport in mySports.SportingItems
orderby eachSport.SportingItemID ascending
select new
{
eachSport.SportingItemID,
eachSport.Name,
eachSport.Description,
eachSport.QuantityOnHand
};
dataGridSport.DataSource = allSport.ToList();
var allHealth = from eachHealth in mySports.HealthItems
orderby eachHealth.HealthItemID ascending
select new
{
eachHealth.HealthItemID,
eachHealth.Name,
eachHealth.Description,
eachHealth.QuantityOnHand
};
dataGridHealth.DataSource = allHealth.ToList();
}
private void moveToHealth_Click(object sender, EventArgs e)
{
//Retrieve selected row and id
var selectedRow = dataGridSport.CurrentRow;
int selectedID = (int)selectedRow.Cells["SportingItemID"].Value;
var data2 = new HealthItem();
var rowToDelete = (from row in mySports.SportingItems
where row.SportingItemID == selectedID
select row).Single();
var rowToAdd = (from row in mySports.SportingItems
where row.SportingItemID == selectedID
select row).Single();
mySports.SportingItems.Remove(rowToDelete); //Mark for deletion
mySports.HealthItems.Add(data2);
mySports.SaveChanges();
RefreshGrids();
}
I'm completely new to databases and EF but I made a database with EF and have a DataGridView control on a windows form that I made by dragging my datasource to my form. After the user enters their information and hits the save button it succesfully saves their information in the database using this code
public partial class bsMainPage : Form
{
BSDATAContainer db = new BSDATAContainer();
public bsMainPage()
{
InitializeComponent();
}
private void saveBtn_Click(object sender, EventArgs e)
{
BSRecords breakfastRecord = new BSRecords();
breakfastRecord.BS = brkBS.ToString();
breakfastRecord.Carbs = brkCarb.ToString();
breakfastRecord.Notes = brkftNoteTxt.Text;
breakfastRecord.Date = dateTxt.Text;
BSRecords lunchRecord = new BSRecords();
lunchRecord.BS = lchBS.ToString();
lunchRecord.Carbs = lchCarb.ToString();
lunchRecord.Notes = lnchNoteTxt.Text;
lunchRecord.Date = dateTxt.Text;
BSRecords dinnerRecord = new BSRecords();
dinnerRecord.BS = dnrBS.ToString();
dinnerRecord.Carbs = dnrCarb.ToString();
dinnerRecord.Notes = dnnrNoteTxt.Text;
dinnerRecord.Date = dateTxt.Text;
db.BSRecords.Add(breakfastRecord);
db.BSRecords.Add(lunchRecord);
db.BSRecords.Add(dinnerRecord);
db.SaveChanges();
}
}
But it doesn't show up in the database until I restart the program. When the user selects a row in the DataGridView and hits the delete button which has this code
private void deleteRowsBtn_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow item in this.bSRecordsDataGridView.SelectedRows)
{
bSRecordsDataGridView.Rows.RemoveAt(item.Index);
}
db.SaveChanges();
}
It deletes the data in the DataGridView but doesn't save the changes in my database. I have followed all the answers I found on here and other sites to delete in the database but nothing will save the deleted changes. Does anyone have any idea how to make it work?
You can delete it using remove. You will need to get the key/id field so without seeing the grid and assuming it is say in a hidden first column:
private void deleteRowsBtn_Click(object sender, EventArgs e)
{
string delId;
BSRecords deleteRecord;
foreach (DataGridViewRow item in this.bSRecordsDataGridView.SelectedRows)
{
bSRecordsDataGridView.Rows.RemoveAt(item.Index);
// code to remove record from database
delId = item.Cells[0].Value.ToString(); // column that has id field
deleteRecord = db.BSRecords.First(b => b.Id == delId); // get the record. will throw exception if not found.
db.BSRecords.Remove(deleteRecord);
}
db.SaveChanges();
bSRecordsDataGridView.DataBind(); // this will refresh your grid. Do same in save.
}
Also note you can rewrite this code:
BSRecords breakfastRecord = new BSRecords();
breakfastRecord.BS = brkBS.ToString();
breakfastRecord.Carbs = brkCarb.ToString();
breakfastRecord.Notes = brkftNoteTxt.Text;
breakfastRecord.Date = dateTxt.Text;
with an object initializer:
BSRecords breakfastRecord = new BSRecords { BS = brkBS.ToString(),
Carbs = brkCarb.ToString(),
Notes = brkftNoteTxt.Text,
Date = dateTxt.Text };
I have a GridControl which contains the List of items with Checkbox control in it.
I am adding & removing the ID to custom List<int> which contains the checked item column ID value. Now, i wan to loop through the List<int> and select the record from Table and by fetching these checked item want to insert in other table using Linq to Entity in WPF using C#.
List<Infill> infillList = new List<Infill>();
List<int> infillListIDs=new List<int>();
private bool ProcessItem(bool IsChecked)
{
bool result = false;
Infill item = grdInfillInner.FocusedRow as Infill;
if (IsChecked)
{
if (item != null)
{
// DO STUFF HERE EXAMPLE ADD or REMOVE Item to a list, BASED on CHECKED or UNCHECKED!!!
int infillid = item.InfillID;
infillListIDs.Add(infillid);
result = true;
}
}
else
{
if(infillListIDs.Contains(item.InfillID))
{
// if uncheked the checked item then remove from custom list
infillListIDs.Remove(item.InfillID);
}
}
grdInfillInner.FocusedRowHandle = -1;
return result;
}
private void BtnInsert_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Total Items :" + infillListIDs.Count);
//Insert the record in other table (having same table structure)
//here by selecting from infillListIDs custom list of type List<int>
}
private void CheckEdit_Checked(object sender, RoutedEventArgs e)
{
e.Handled = ProcessItem(true);
}
private void CheckEdit_Unchecked(object sender, RoutedEventArgs e)
{
e.Handled = ProcessItem(false);
}
protected void GetAllInfills()
{
List<Infill> infillList = new List<Infill>();
infillList=BLL.GetAllInfills();
if (infillList != null)
{
grdInfill.ItemsSource = infillList;
grdInfill.GroupBy(grdInfill.Columns["Glass.GlassType"], ColumnSortOrder.Ascending);
grdInfill.GroupBy(grdInfill.Columns["Glass.Glass_Description"], ColumnSortOrder.Ascending);
grdInfill.AutoExpandAllGroups = true;
}
}
I want to fetch the records from infill table where infillListIDs containing IDs of all checked rows from Infill table and insert into DummyInfill table having same structure when insert button is clicked!
See this: https://stackoverflow.com/a/15829249/265100
Get the objects that have matching IDs and add to the new table.
Using (DB _db = new DB()){
foreach(Infill inf in InfillCol){
DummyInfill.Add(inf);
}
DummyInfill.SaveChanges();
}
I don't know what version of EF you are using but l understand that you can implement SQLBulkCopy.
See this post: https://stackoverflow.com/a/1610014/265100
I want to delete the selected rows from DataGridView and this delete should affect the database. I'm using the Entity Framework and that is my code which did not work.
private void button4_Click(object sender, EventArgs e)
{
var toBeDeleted = (int)dataGridView1.SelectedRows[0].Cells[0].Value;
var TE = new TaskEntities();
var UD = new userdata();
UD = TE.userdatas.First(c => c.ID == toBeDeleted);
TE.DeleteObject(UD);
TE.SaveChanges();
}
Is your DGV bound to any dataSource?
Is so, delete row from datasource, and then do use Update command (or update sql query) to do chnages in database.
try this:
private void button4_Click(object sender, EventArgs e)
{
var toBeDeleted = (int)dataGridView1.SelectedRows[0].Cells[0].Value;
var TE = new TaskEntities();
var userdata = TE.userdatas.First(c => c.ID == toBeDeleted);
TE.userdatas.Remove(userdata);
TE.SaveChanges();
dataGridView1.DataSource = TE.userdatas;
}