C# A bindinglist saves me the null value in json - c#

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

Related

C# Linq To SQL to Fill a DataGrid and and get fields into a TextBox

In C# i can easily get data from a SQL DataBase and put it in a DataGrid with this code :
private void GetPcListBtn_Click(object sender, RoutedEventArgs e)
{
string service = (string)ServiceCB.SelectedValue;
comm = new SqlCommand("select T_COLLABORATEURS.CO_IDENT,T_PC.PC_ID,T_PC.PC_NOM,T_PC.PC_MODEL," +
"T_PC.PC_DATE_MES,T_PC.PC_COMM,T_PC.SERV_ID from T_COLLABORATEURS, T_PC" +
$" where T_COLLABORATEURS.CO_ID = T_PC.CO_ID and T_PC.SERV_ID = '{service}' ", conn);
SqlDataAdapter dap = new SqlDataAdapter(comm);
DataTable dt = new DataTable();
dap.Fill(dt);
PC_DT.ItemsSource = dt.DefaultView;
}
Then on Datagrid SelectionChanged Event i can click on a row to get fields datas and put it in a texbox with this code :
// DataGrid SelectionChanged => Fill TexBox
private void PC_DT_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (PC_DT.SelectedItem is DataRowView oData)
{
string pcNom = (string)oData["PC_NOM"];
string pcModel = (string)oData["PC_MODEL"];
RefPcTxtBox.Text = $"{pcNom} / {pcModel}";
}
}
Now in a other application i want to use Linq To SQL to do exactly the same.
Fill DataGrid :
// Fill DataGrid
private void GetPcListBtn_Click(object sender, RoutedEventArgs e)
{
string service = (string)ServiceCB.SelectedValue;
DataClasses1DataContext dc = new DataClasses1DataContext();
var pcCo = from co in dc.T_COLLABORATEURS
join pc in dc.T_PC on co.CO_ID equals pc.CO_ID
where pc.SERV_ID == service
select new
{
pc.PC_ID,
co.CO_IDENT,
pc.PC_NOM,
pc.PC_MODEL,
pc.PC_DATE_MES,
pc.PC_COMM,
pc.SERV_ID
};
PC_DT.ItemsSource = pcCo;
}
But now how can i fill my TextBox by clicking a DataGrid row ??
private void PC_DT_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// How to Fill my Textbox ??
}
Please try this.
First way:
// Or whenever grid you want to use please set this type
var Grid = sender as DataGrid;
if(Grid != null)
{
textbox = Grid.FieldName
}
Second way:
var currentRow = GridName.SelectedRows;
if(currentRow != null)
{
textbox = currentRow .FieldName
}

Delete row in DataGridView and database

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

Cannot assign selected value from combobox to variable in SelectedIndexChanged event. Fill textboxes by combobox selection C# Winforms

In this form user update data about Client in client table. When form is loaded it fills textboxes whis data from client table by value in combobox. When user change value in combobox data int textboxes must change.
But when I am trying to get Client ID from selected value in combobox event and assign it to getClientID variable compiler gives me error:
System.FormatException : Input string was not in a correct format.
private void ClientUpdateForm_Load(object sender, EventArgs e)
{
ClientComboBox.DataSource = AgencyContext.Client.ToList();
ClientComboBox.DisplayMember = "ClientName";
ClientComboBox.ValueMember = "ClientID";
Invalidate();
int getClientID = Convert.ToInt32(ClientComboBox.SelectedValue.ToString());
var fillTextBoxes = (from t in AgencyContext.Client where t.ClientID == getClientID select t).Single();
ClientNametextBox.Text = fillTextBoxes.ClientName;
ClientBirthtextBox.Text = fillTextBoxes.Birth.ToString(CultureInfo.CurrentCulture);
ClientPhonetextBox.Text = fillTextBoxes.Phone.ToString();
ClientPassporttextBox.Text = fillTextBoxes.Passport;
AddresstextBox.Text = fillTextBoxes.Address;
ClientStatetextBox.Text = fillTextBoxes.State;
ClientCitytextBox.Text = fillTextBoxes.City;
}
private void SaveNewClientButton_Click(object sender, EventArgs e)
{
}
private void ClientComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
var getClientID = Convert.ToInt32(ClientComboBox.SelectedValue.ToString());
var fillTextBoxes = (from t in AgencyContext.Client where t.ClientID == getClientID select t).Single();
ClientNametextBox.Text = fillTextBoxes.ClientName;
ClientBirthtextBox.Text = fillTextBoxes.Birth.ToString(CultureInfo.CurrentCulture);
ClientPhonetextBox.Text = fillTextBoxes.Phone.ToString();
ClientPassporttextBox.Text = fillTextBoxes.Passport;
AddresstextBox.Text = fillTextBoxes.Address;
ClientStatetextBox.Text = fillTextBoxes.State;
ClientCitytextBox.Text = fillTextBoxes.City;
}
During the load event ... there is no selected value ... it is null and cannot be converted to int. You have to wait until after databinding before you pull the selected value.

BindingList when load items

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

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

Categories

Resources