BindingList when load items - c#

I have this on framework v3.5 PRJ
public BindingList<BackupItem> bb = new BindingList<BackupItem>();
when
private void Form1_Load(object sender, EventArgs e)
{
checkedListBox1.DataSource = bb;
checkedListBox1.DisplayMember = "backupName";
}
I have implement add/edit/delete 'touching' only the BindingList all working as expected, at the end going to save/load the BindingList contents.
-Save done -Load done
hmm when loading the records not appear at checkedListBox1 !!
To display the records, I have to re init checkedListBox1 with
private void toolStripJSONLoad_Click(object sender, EventArgs e)
{
string tmp = File.ReadAllText(#"D:\path.txt", Encoding.UTF8);
JavaScriptSerializer oSerializer = new JavaScriptSerializer();
bb = oSerializer.Deserialize<BindingList<BackupItem>>(tmp);
checkedListBox1.DataSource = null;
checkedListBox1.DataSource = bb;
checkedListBox1.DisplayMember = "backupName";
}
anyone knows anything?

The statement:
bb = oSerializer.Deserialize<BindingList<BackupItem>>(tmp);
is creating a whole new object, pointing to a different memory location from where checkedListBox1.DataSource is pointing to.
What you need to do is modify the content of the bb variable. First clear the content then add the new items. Something like this:
private void toolStripJSONLoad_Click(object sender, EventArgs e)
{
string tmp = File.ReadAllText(#"D:\path.txt", Encoding.UTF8);
JavaScriptSerializer oSerializer = new JavaScriptSerializer();
var tmpObj = oSerializer.Deserialize<List<BackupItem>>(tmp);
bb.Clear();
tmpObj.ForEach(o => bb.Add(o));
}

Related

C# A bindinglist saves me the null value in json

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>;

C# ComboBox SelectedItem.toString() not returning expected results

I have a form that allows a user to add players to a roster, by entering the player name and selecting, from a combo box, the division to which the player belongs.
When time comes to add the player to my TreeView control, the node that should display the division selected displays this text instead: System.Data.DataRowView
I got the code to implement this through MSDN here: https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selecteditem%28v=vs.110%29.aspx
Here's the code in the load function of the form, to fill the combo box:
private void frm_add_players_Load(object sender, EventArgs e)
{
Divisions divs = new Divisions();
Players players = new Players();
DataTable dtDivisions = divs.GetActiveDivisions(); //divisions combo box
DataTable dtPlayers = players.GetPlayersByTourID(this.tourID);
//set the forms datatable
this.dt_players = dtPlayers;
//fill the combo box
this.cmbo_divisions.DataSource = dtDivisions;
this.cmbo_divisions.DisplayMember = "title";
this.cmbo_divisions.ValueMember = "ID";
this.cmbo_divisions.SelectedIndex = -1;
this.cmbo_divisions.Text = "Select a Division";
//set treeview imagelist
this.tview_roster.ImageList = tview_imagelist;
this.tview_roster.ImageIndex = 1; //division icon
//fill treeview
foreach (DataRow dr in dtPlayers.Rows)
{
FillPlayerTreeview(dr);
}
//expand treeview
this.tview_roster.ExpandAll();
this.ActiveControl = this.txt_player_name;
}
Here I call the function to add the player to the TreeView:
private void btn_add_Click(object sender, EventArgs e)
{
object selItem = cmbo_divisions.SelectedItem;
AddPlayerToTreeView(txt_player_name.Text, selItem.ToString());
}
And here is the function that adds the player:
private void AddPlayerToTreeView(string playerName, string division)
{
TreeNode[] tns = this.tview_roster.Nodes.Find(division, false); //try to find the division, if exists
TreeNode tn = new TreeNode();
if (tns.Length > 0) //division exists - add player
{
tn = this.tview_roster.Nodes[tns[0].Index].Nodes.Add(playerName, playerName);
tn.ImageIndex = 0; //player icon
}
else //division doesn't exist - add division, then add player
{
tn = this.tview_roster.Nodes.Add(division, division);
tn.ImageIndex = 1; //division icon
AddPlayerToTreeView(playerName, division);
}
}
And the result is this:
I'm not sure why it won't work.. and I'm at a loss. Any help would be appreciated.
Well, well... maybe something like the following.
Access the combo's data source, which is a DataTable, and extract selected row and column value using selected index. Maybe add some error handling, too.
private void btn_add_Click(object sender, EventArgs e)
{
var data = cmbo_divisions.DataSource as DataTable;
var row = data.Rows[cmbo_divisions.SelectedIndex];
var selected = row["title"].ToString();
AddPlayerToTreeView(txt_player_name.Text, selected);
}
Try this :
private void btn_add_Click(object sender, EventArgs e)
{
object selItem = cmbo_divisions.SelectedItem;
AddPlayerToTreeView(txt_player_name.Text, cmbo_divisions.SelectedItem as string);
}
ToString() will get the type name, but in that case the SelectedItem is a string.
Try with:
private void btn_add_Click(object sender, EventArgs e)
{
AddPlayerToTreeView(txt_player_name.Text, cmbo_divisions.Items[cmbo_divisions.SelectedIndex].Text);
}
EDIT: Updated to a better way

Read/Load xml file by form loading using c#

I'm writing a program which add items to DataGridView and save the inputs to an xml file which is created by clicking button (if not exists). This works fine. But if I restart the program it should load every item to DataGridView. But I have to add a new item first and then all the other items are displayed. So the items won't load if Form1 load. I think I have to put some code in Form1_Load() but I don't have an idea. I tried to put XElement.Load(); in Form1_Load() but no success. Here you can see my code:
XElement xmlFile;
XElement xmlnode;
private void Form1_Load(object sender, EventArgs e)
{
xmlFile = XElement.Load(#"C:\Users\rs\Desktop\Save\save.xml");
xmlFile.Add(xmlnode);
}
private void btnSave_Click(object sender, EventArgs e)
{
if (!File.Exists(#"C:\Users\rs\Desktop\Save\save.xml"))
{
using (File.Create(#"C:\Users\rs\Desktop\Save\save.xml")) { }
}
xmlnode = new XElement("iToDo",
new XElement("Name", txtName.Text),
new XElement("Priority", comPrio.Text),
new XElement("StartDate", txtStart.Text),
new XElement("EndDate", txtEnd.Text),
new XElement("Comment", txtComment.Text)
);
try
{
xmlFile = XElement.Load(#"C:\Users\rs\Desktop\Save\save.xml");
xmlFile.Add(xmlnode);
}
catch (XmlException)
{
xmlFile = new XElement("ToDos", xmlnode);
}
xmlFile.Save(#"C:\Users\rs\Desktop\Save\save.xml");
DataSet flatDataSet = new DataSet();
flatDataSet.ReadXml(#"C:\Users\rs\Desktop\Save\save.xml");
DataTable table = flatDataSet.Tables[0];
dataGridToDo.DataSource = table;
}
Someone got an idea or can give me a hint?
Thanks in advance
Cheers
You will have to put this in the form1_load method:
DataSet flatDataSet = new DataSet();
flatDataSet.ReadXml(#"C:\Users\rs\Desktop\Save\save.xml");
DataTable table = flatDataSet.Tables[0];
dataGridToDo.DataSource = table;
I've created your app now, here's my Form1_Load method:
private void Form1_Load(object sender, EventArgs e)
{
xmlFile = XElement.Load(#"C:\save.xml");
xmlFile.Add(xmlnode);
DataSet flatDataSet = new DataSet();
flatDataSet.ReadXml(#"C:\save.xml");
DataTable table = flatDataSet.Tables[0];
dataGridToDo.DataSource = table;
}
When I run the app, then my datagrid gets filled with the xml data.

databind entityframework ObjectSet<T> to a gridcontrol (c#)

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();
}

DevExpress DataBinding, Add new Record

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..

Categories

Resources