I am using DevExpress EntityInstantFeedbackSource as datasource to an XtraGrid control. However I am not using the connection string from the app.config file; rather I am setting the connection string for entity framework at runtime.
The code is given below:
void Form1_Load(object sender, EventArgs e)
{
entityInstantFeedbackSource1.KeyExpression = "Prodid";
entityInstantFeedbackSource1.GetQueryable += entityInstantFeedbackSource1_GetQueryable;
entityInstantFeedbackSource1.DismissQueryable += entityInstantFeedbackSource1_DismissQueryable;
gridControl1.DataSource = null;
gridControl1.DataSource = entityInstantFeedbackSource1;
}
void entityInstantFeedbackSource1_GetQueryable(object sender, GetQueryableEventArgs e)
{
EntityConnectionStringBuilder ecsb = new EntityConnectionStringBuilder();
ecsb.Metadata = #"res://*/Model2.csdl|res://*/Model2.ssdl|res://*/Model2.msl";
ecsb.Provider = #"System.Data.SqlClient";
ecsb.ProviderConnectionString = #"data source=.\sqlexpress;initial catalog=AdventureWorks; integrated security=True;MultipleActiveResultSets=True;App=EntityFramework";
using (var context = new ObjectContext(ecsb.ConnectionString))
{
context.DefaultContainerName = "AdventureWorksEntities";
ObjectSet<Person> query = context.CreateObjectSet<Person>();
var q = from s in query
select s;
e.QueryableSource = q;
e.Tag = context;
}
}
void entityInstantFeedbackSource1_DismissQueryable(object sender, GetQueryableEventArgs e)
{
((ObjectContext)e.Tag).Dispose();
}
The grid is blank. However if I write a foreach loop around 'query' and view the output in Console.WriteLine then I can see the data.
Also if I set e.QueryableSource = q.ToArray().AsQueryable() then I can see data in the grid. But doing this will load all data at one time there by nullifying the benefit of EntityInstantFeedbackSource.
Why there is no data in query? And how to databind ObjectSet to a gridcontrol?
I believe the reason of this issue is that you are disposing the ObjectContext directly in GetQueryable handler rather then to do it in DismissQueryable only. Moreover you can pass the resulting object set directly to e.QuerableSource.
Thus the correct code should looks like this:
void entityInstantFeedbackSource_GetQueryable(object sender, DevExpress.Data.Linq.GetQueryableEventArgs e) {
//... connection initialization ...
var context = new ObjectContext(ecsb.ConnectionString);
ObjectSet<Person> personSet = context.CreateObjectSet<Person>();
e.QueryableSource = personSet;
e.Tag = context;
}
void entityInstantFeedbackSource_DismissQueryable(object sender, DevExpress.Data.Linq.GetQueryableEventArgs e) {
((ObjectContext)e.Tag).Dispose();
}
Related
When i save the json file i hold only a null value, why?
Il'l want to view my datagridview e add in it some row then i'ld want to save the table in a file
private void btn_Salva_Click(object sender, EventArgs e)
{
var listadasalvare = dataGridView1.DataSource as List<Rubrica>;
var listaJson = JsonConvert.SerializeObject(listadasalvare);
// indico direttamente il percorso senza richiamare la finestra
// di salvataggio
var path = #"D:\OneDrive\Corso di c# informatica\Rubricajsonformato.txt";
File.WriteAllText(path, listaJson);
}
private void Form1_Load(object sender, EventArgs e)
{
var formcreate = ClientiDataManager.GetClienti();
var telefonia = new BindingList<Rubrica>();
foreach (var campo in formcreate)
{
var nuovatelefonia = new Rubrica();
nuovatelefonia.IdScheda = campo.IdScheda;
nuovatelefonia.Intestatario = campo.Intestatario;
nuovatelefonia.NumeroTelefono = campo.NumeroTelefono;
nuovatelefonia.Scadenza = campo.Scadenza;
telefonia.Add(nuovatelefonia);
}
dataGridView1.DataSource = telefonia;
}
The issue is listadasalvare is null. In the form load event, var telefonia = new BindingList<Rubrica>(); is a BindingList<Rubrica> and it is used as a DataSource to the grid. Therefore, when the code cast it as a List<Rubrica> in the button click, it will return null. Try…
var listadasalvare = dataGridView1.DataSource as BindingList<Rubrica>;
At the beginning, when I assign my collection to a control's DataSource, it follows what is in the collection. During the execution of my program, when the collection changes, I don't see any change in the control's content. How can I make the control follow the latest changes of the collection?
What I have is:
private void FormEditImages_Load(object sender, EventArgs e)
{
radListView1.DataSource = WebServiceHelper.Instance.CurrentSession.Images;
radListView1.DisplayMember = "Name";
radListView1.ValueMember = "Id";
}
private void radListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
var cameraOverlayImage = e.Item.DataBoundItem as CameraOverlayImage;
e.Item.Image = CreateThumbnail(cameraOverlayImage.Image, e.ListViewElement.ItemSize.Width - 12, e.ListViewElement.ItemSize.Height - 16, e.ListViewElement.BackColor);
e.Item.TextAlignment = ContentAlignment.MiddleCenter;
e.Item.TextImageRelation = TextImageRelation.ImageAboveText;
e.Item.ImageAlignment = ContentAlignment.MiddleCenter;
}
How can I change the ItemDataBound method when I change Load to:
private void FormEditImages_Load(object sender, EventArgs e)
{
var bindingSource = new BindingSource(WebServiceHelper.Instance.CurrentSession.Images, "Name");
radListView1.DataSource = bindingSource;
}
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 am using EntityFramework.
The DELETE function will delete the selected customer and refresh the datagridview, but the ADD function did not refresh the datagridview with the new added customer. Any idea?
public CustomerDialog()
{
InitializeComponent();
nw = new northwindEntities();
}
private void CustomerDialog_Load(object sender, EventArgs e)
{
dgvCustomer.DataSource = nw.Customers;
}
private void btnDelete_Click(object sender, EventArgs e)
{
string strSelectedCustomerID = getSelectedCustomerID();
Customer customer = nw.Customers.Where(a => a.CustomerID == strSelectedCustomerID).First();
nw.Customers.DeleteObject(customer);
nw.SaveChanges();
}
//the new customer is persist on the database, but the dgvCustomer is not update.
private void btnAdd_Click(object sender, EventArgs e)
{
Customer newCustomer = new Customer() {
CustomerID = txtCustomerID.Text,
CompanyName = txtCompanyName.Text,
ContactName = txtContactName.Text
};
nw.Customers.AddObject(newCustomer);
nw.SaveChanges();
dgvCustomer.DataSource = nw.Customers ;
dgvCustomer.Refresh();
}
You may try calling BindingSource.ResetBindings() method after you called the SaveChanges() method.
Also, it could help to use a BindingList as the data source (see the article's code example how to use it).
Ugly, but pragmatic approach: dgvCustomer.DataSource = null; dgvCustomer.DataSource = nw.Customers;
As a side note, dgvCustomer.Refresh() will not help you in this case. It does not refresh the data binding, it will cause the control to redraw itself in the UI, which most is likely not what you intended.
I am using DevExpress in my winform application, I have a gridview, data entry form, datanavigator, all bound to dataset.
I want to add new record, if using datanavigator "Add" it works good, how to do the same using a "New Record" button?
BindingSource.AddNew()
is not working, it usually does, but with devexpress its not working.
If you want to use binding then use your objects with binding source..
and use the binding list .AddingNew += new AddingNewEventHandler(listOfParts_AddingNew);
event to add new entity object ..
See the example of BindingList on MSDN.
void listOfParts_AddingNew(object sender, AddingNewEventArgs e)
{
e.NewObject = new Part(textBox1.Text, int.Parse(textBox2.Text));
}
DevExpress WinForm Controls works so fast with binding sources as compare to typed datasources etc... YOu can implement bindingSources using these example..
set gridview and the associcated controls datasource to bindsouce that you have created...
process your form with the this MSDN example..
have a look on this code snippet.. may be you will get some idea from this..
private void BindingLIstDemo_Load(object sender, EventArgs e)
{
InitializeListOfEmployees();
BindlstEmp();
listofEmp.AddingNew += new AddingNewEventHandler(listOfEmp_AddingNew);
listofEmp.ListChanged += new ListChangedEventHandler(listofEmp_ListChanged);
}
private void BindlstEmp()
{
lstEmpList.Items.Clear();
lstEmpList.DataSource = listofEmp;
lstEmpList.DisplayMember = "Name";
}
void listofEmp_ListChanged(object sender, ListChangedEventArgs e)
{
MessageBox.Show(e.ListChangedType.ToString());
//throw new NotImplementedException();
}
//declare list of employees
BindingList<Emp> listofEmp;
private void InitializeListOfEmployees()
{
//throw new NotImplementedException();
// Create the new BindingList of Employees.
listofEmp = new BindingList<Emp>();
// Allow new Employee to be added, but not removed once committed.
listofEmp.AllowNew = true;
listofEmp.AllowRemove = true;
// Raise ListChanged events when new Employees are added.
listofEmp.RaiseListChangedEvents = true;
// Do not allow Employee to be edited.
listofEmp.AllowEdit = false;
listofEmp.Add(new Emp(1, "Niranjan", 10000));
listofEmp .Add (new Emp (2,"Jai", 8000));
}
// Create a new Employee from the text in the two text boxes.
void listOfEmp_AddingNew(object sender, AddingNewEventArgs e)
{
e.NewObject = new Emp (Convert.ToInt32(txtId.Text), txtName.Text,Convert.ToInt32(txtSalary.Text));
}
private void btnAdd_Click(object sender, EventArgs e)
{
Emp empItem = listofEmp.AddNew();
txtId.Text = txtName.Text = txtSalary.Text = "";
}
private void button1_Click(object sender, EventArgs e)
{
Form1 obj = new Form1();
obj.Show();
}
private void btnDelete_Click(object sender, EventArgs e)
{
var sg = (from sc in listofEmp.ToList<Emp>() where sc.Name == ((Emp)lstEmpList.SelectedValue).Name select sc);
}
private void lstEmpList_SelectedIndexChanged(object sender, EventArgs e)
{
Emp se = listofEmp[lstEmpList.SelectedIndex];
txtId.Text = se.Id.ToString();
txtName.Text = se.Name;
txtSalary.Text = se.Salary.ToString();
}
Here I am using BindingList as datasouce BindingList<Emp> listofEmp; and on the place of grid listing of records are shown in a listbox control.. but all same...try this with your gridview..