DbContext.SaveChanges() does not save the changes to database - winforms

DbContext.SaveChanges() does not save the changes to database but updates the grid. The method that is not working as I would like is in bSave_Click method. How can I force it to update also database?
The code of the Windows Forms application is below:
namespace WinFormsApp
{
public partial class MainForm : Form
{
private List<User> users;
private List<UserType> userTypes;
private List<DataGridViewUserDTO> usersForGrid;
public MainForm()
{
InitializeComponent();
GetData();
PrepareGrid();
FillGrid();
}
public void GetData()
{
using (var dbContext = new DataInFileEntities())
{
userTypes = dbContext.UserTypes.ToList();
users = dbContext.Users.ToList();
usersForGrid = users.Select(x => new DataGridViewUserDTO() { Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, UserTypeId = x.UserTypeId, CreatedById = x.CreatedById, Created = x.Created, EditedById = x.EditedById, Edited = x.Edited }).ToList();
}
}
public void FillGrid()
{
var gridBindingList = new BindingList<DataGridViewUserDTO>(usersForGrid);
gridBindingSource = new BindingSource(gridBindingList, null);
dgvUsers.DataSource = gridBindingSource;
}
public void PrepareGrid()
{
dgvUsers.AutoGenerateColumns = false;
DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
col.DataPropertyName = "Id";
col.HeaderText = "Id";
col.Name = "Id";
col.ReadOnly = true;
col.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
dgvUsers.Columns.Add(col);
col = new DataGridViewTextBoxColumn();
col.DataPropertyName = "FirstName";
col.HeaderText = "First Name";
col.Name = "FirstName";
dgvUsers.Columns.Add(col);
col = new DataGridViewTextBoxColumn();
col.DataPropertyName = "LastName";
col.HeaderText = "Last Name";
col.Name = "LastName";
dgvUsers.Columns.Add(col);
DataGridViewComboBoxColumn userTypeCol = new DataGridViewComboBoxColumn();
userTypeCol.DataPropertyName = "UserTypeId";
userTypeCol.HeaderText = "User Type";
userTypeCol.Name = "UserTypeId";
userTypeCol.DataSource = new BindingList<UserType>(userTypes);
userTypeCol.DisplayMember = "Name";
userTypeCol.ValueMember = "Id";
dgvUsers.Columns.Add(userTypeCol);
col = new DataGridViewTextBoxColumn();
col.DataPropertyName = "Edited";
col.HeaderText = "Edited";
col.Name = "Edited";
col.ReadOnly = true;
dgvUsers.Columns.Add(col);
DataGridViewComboBoxColumn editedByCol = new DataGridViewComboBoxColumn();
editedByCol.DataPropertyName = "EditedById";
editedByCol.HeaderText = "Edited By";
editedByCol.Name = "EditedById";
editedByCol.DataSource = new BindingList<DataGridViewUserDTO>(usersForGrid);
editedByCol.DisplayMember = "Name";
editedByCol.ValueMember = "Id";
editedByCol.ReadOnly = true;
dgvUsers.Columns.Add(editedByCol);
col = new DataGridViewTextBoxColumn();
col.DataPropertyName = "Created";
col.HeaderText = "Created";
col.Name = "Created";
col.ReadOnly = true;
dgvUsers.Columns.Add(col);
DataGridViewComboBoxColumn createdByCol = new DataGridViewComboBoxColumn();
createdByCol.DataPropertyName = "CreatedById";
createdByCol.HeaderText = "Created By";
createdByCol.Name = "CreatedById";
createdByCol.DataSource = new BindingList<DataGridViewUserDTO>(usersForGrid);
createdByCol.DisplayMember = "Name";
createdByCol.ValueMember = "Id";
createdByCol.ReadOnly = true;
dgvUsers.Columns.Add(createdByCol);
}
private void bSave_Click(object sender, EventArgs e)
{
using (var dbContext = new DataInFileEntities())
{
foreach (var row in usersForGrid)
{
var dbItem = dbContext.Users.Where(x => x.Id == row.Id).SingleOrDefault();
if (dbItem != null)
{
if (dbItem.FirstName != row.FirstName || dbItem.LastName != row.LastName || dbItem.UserTypeId != row.UserTypeId)
{
dbItem.FirstName = row.FirstName;
dbItem.LastName = row.LastName;
dbItem.UserTypeId = row.UserTypeId;
dbItem.Edited = DateTime.UtcNow;
dbItem.EditedById = 1;
}
}
}
dbContext.SaveChanges();
}
GetData();
FillGrid();
}
}
public class DataGridViewUserDTO
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Name { get { return FirstName + " " + LastName; }}
public byte UserTypeId { get; set; }
public Nullable<System.DateTimeOffset> Edited { get; set; }
public Nullable<int> EditedById { get; set; }
public System.DateTimeOffset Created { get; set; }
public int CreatedById { get; set; }
}
}

Related

'There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'InternID'.'

i'm new to ASP.NET MVC
so i've been trying for the last week to create a dropdown list from sql server to view a list of the interns Names
I've tried various & different ways to solve it, i checked most of the stackoverflow solutions related to the same issue, but all is leading to is the same error 'There is no ViewData item of type 'IEnumerable' that has the key 'InternID'.'
So my question is, What am i missing?
this is my main code
Controller
public ActionResult AddTask(Add_TaskModel Add_Task, HttpPostedFileBase postedFile) {
var InternList = entities.InternsTbls.ToList();
ViewBag.internList = new SelectList(InternList, "InternID","Name");
return View();}
View
#Html.DropDownListFor(m => m.InternID, ViewBag.internList as SelectList, "--Select The Intern", new { #class = "form-cotrnol"})
Model
public class Add_TaskModel
{
[Key]
public int TaskID { get; set; }
public string TaskTitle { get; set; }
public string TaskType { get; set; }
public string TaskDes { get; set; }
public string DueDate { get; set; }
public int SupID { get; set; }
public string TaskStatus { get; set; }
public int FileID { get; set; }
public int InternID { get; set; }
public string Name { get; set; }
}
Note- this one of many ways i tried, but same error.
Code 2
//var myList = new List<SelectListItem>();
//var list = entities.InternsTbls.ToList();
//var items = from g in list
// select new SelectListItem
// {
// Value = g.InternID.ToString(),
// Text = g.Name.ToString()
// };
//foreach (var item in items)
// myList.Add(item);
//ViewBag["In_List"] = myList;
Code 3
//string mainconn = ConfigurationManager.ConnectionStrings["TaskTrackerDBEntities"].ConnectionString;
//if (mainconn.ToLower().StartsWith("metadata="))
//{
// System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder efBuilder = new System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder(mainconn);
// mainconn = efBuilder.ProviderConnectionString;
//}
//using (SqlConnection sqlconn = new SqlConnection(mainconn))
//{
// string sqlquery = "select * from [dbo].[InternsTbl]";
// using (SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn))
// {
// sqlconn.Open();
// SqlDataAdapter sda = new SqlDataAdapter(sqlcomm);
// DataSet ds = new DataSet();
// sda.Fill(ds);
// ViewBag.internname = ds.Tables[0];
// List<SelectListItem> getinternname = new List<SelectListItem>();
// foreach (System.Data.DataRow dr in ViewBag.internname.Rows)
// {
// getinternname.Add(new SelectListItem { Text = #dr["Name"].ToString(), Value = #dr["Name"].ToString() });
// }
// ViewData ["Interns"] = getinternname;
// //new SelectList(getinternname, "Name", "Name");
// sqlconn.Close();
// }
//}
Code 4
//TaskTrackerDBEntities entities1 = new TaskTrackerDBEntities();
//var getInternName = entities1.InternsTbls.ToList();
//SelectList list = new SelectList(getInternName, "InternID", "Name");
// ViewBag["InternListName"] = list;
//ViewBag.SubNames = new SelectList(entities1.InternsNames, "InternID", "Name");

Call Apex Method from the Custom Button

I created a Apex Class like
Public class test_Controller
{
Public test_Controller() { }
Public void send(set<id> oppIds)
{
List<Oppurtunity> OppLst =[Select Name from Opportunity where id IN: oppIds];
Private static string integration_key = 'abcd';
Private static string account_id = 'efgh';
Public string signer_email { get; set; }
Public string signer_name { get; set; }
Public string email_message { get; set; }
Public string output { get; set; }
Public string envelope_id { get; set; }
Public string error_code { get; set; }
Public string error_message { get; set; }
Private static string ds_server = 'callout:DocuSign_Legacy_Demo/api/3.0/dsapi.asmx';
Private static string trace_value = 'SFDC_004_SOAP_email_send'; // Used for tracing API calls
Private static string trace_key = 'X-ray';
Private DocuSignTK.APIServiceSoap api_sender = new DocuSignTK.APIServiceSoap();
configure_sender();
do_send(OppLst);
}
Private void configure_sender()
{
api_sender.endpoint_x = ds_server;
api_sender.inputHttpHeaders_x = new Map<String, String>();
String auth = '<DocuSignCredentials><Username>{!$Credential.Username}</Username>'
+ '<Password>{!$Credential.Password}</Password>'
+ '<IntegratorKey>' + integration_key + '</IntegratorKey></DocuSignCredentials>';
api_sender.inputHttpHeaders_x.put('X-DocuSign-Authentication', auth);
}
Private void do_send(List<Oppurtunity> OppurLst)
{
if (integration_key == 'xxx-xxxx-xxxx' ||
account_id == 'xxxx-xxxx-xxxx')
{
error_message = 'Please configure the Apex class DS_Recipe_Send_Env_Email_Controller with your integration key and account id.';
error_code = 'CONFIGURATION_PROBLEM';
return;
}
String file_contents = '<html><h1>Quote Document</h1>' + get_lorem(OppurLst)
+ '<p> </p>'
+ '<p>Signature: <span style="color:white;">signer1sig</span></p>'
+ '<p>Date: <span style="color:white;">signer1date</span></p></html>';
DocuSignTK.Document document = new DocuSignTK.Document();
document.ID = 1;
document.Name = 'Quote Document';
document.FileExtension = 'html';
document.pdfBytes = EncodingUtil.base64Encode(Blob.valueOf(file_contents));
DocuSignTK.Recipient recipient = new DocuSignTK.Recipient();
recipient.Email = '';
recipient.UserName = '';
recipient.ID = 1;
recipient.Type_x = 'Signer';
recipient.RoutingOrder = 1;
DocuSignTK.Tab signHereTab = new DocuSignTK.Tab();
signHereTab.Type_x = 'SignHere';
signHereTab.AnchorTabItem = new DocuSignTK.AnchorTab();
signHereTab.AnchorTabItem.AnchorTabString = 'signer1sig'; // Anchored for doc 1
signHereTab.AnchorTabItem.XOffset = 8;
signHereTab.RecipientID = 1;
signHereTab.Name = 'Please sign here';
signHereTab.ScaleValue = 1;
signHereTab.TabLabel = 'signer1sig';
DocuSignTK.Tab dateSignedTab = new DocuSignTK.Tab();
dateSignedTab.Type_x = 'DateSigned';
dateSignedTab.AnchorTabItem = new DocuSignTK.AnchorTab();
dateSignedTab.AnchorTabItem.AnchorTabString = 'signer1date'; // Anchored for doc 1
dateSignedTab.AnchorTabItem.YOffset = -6;
dateSignedTab.RecipientID = 1;
dateSignedTab.Name = 'Date Signed';
dateSignedTab.TabLabel = 'date_signed';
DocuSignTK.Envelope envelope = new DocuSignTK.Envelope();
envelope.Subject = 'Please sign the Quote Document';
envelope.AccountId = account_id;
envelope.Tabs = new DocuSignTK.ArrayOfTab();
envelope.Tabs.Tab = new DocuSignTK.Tab[2];
envelope.Tabs.Tab.add(signHereTab);
envelope.Tabs.Tab.add(dateSignedTab);
envelope.Recipients = new DocuSignTK.ArrayOfRecipient();
envelope.Recipients.Recipient = new DocuSignTK.Recipient[1];
envelope.Recipients.Recipient.add(recipient);
envelope.Documents = new DocuSignTK.ArrayOfDocument();
envelope.Documents.Document = new DocuSignTK.Document[1];
envelope.Documents.Document.add(document);
if (String.isNotBlank(email_message))
{
envelope.EmailBlurb = email_message;
}
try
{
DocuSignTK.EnvelopeStatus result = api_sender.CreateAndSendEnvelope(envelope);
envelope_id = result.EnvelopeID;
System.debug('Returned successfully, envelope_id = ' + envelope_id);
}
catch (CalloutException e)
{
System.debug('Exception - ' + e);
error_code = 'Problem: ' + e;
error_message = error_code;
}
}
Private Boolean no_error()
{
return (String.isEmpty(error_code));
}
Private static String get_lorem(List<Oppurtunity> OLst)
{
String lorem = 'Hello World';
return lorem;
}
}
And I am trying to call the send Method from the Apex from the Custom Button like
{!REQUIRESCRIPT("/soap/ajax/41.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/41.0/apex.js")}
sforce.apex.execute("test_Controller","send",{oppIds:"{!Opportunity.Id}"});
When I try to execute the button I get the following error message:
A Problem with the OnClick JavaScript for this button or link was
encountered: {faultcode:''soapenv:Client', faultstring:'No operation
available for request
{http://soap.sforce.com/schemas/package/test_Controller}send, please
check the WSDL for the service.'}'
I am new to Salesforce and Apex scripting. Any help is greatly appreciated.
Your method is expecting a list of Ids.
Public void send(set<id> oppIds)
So I am guessing that maybe you need to send it as an array?
sforce.apex.execute("test_Controller","send",{oppIds:["{!Opportunity.Id}"]});
You need to expose this method as a webservice and it needs to be static
webservice static void send(List<Id> oppIds) {
}
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_and_ajax.htm

Error inserting data from many method return lists to a database in c#

I need help here with part of my code so here it is:
I have 6 methods as you can see below that parse incoming data and then returns it as a list, so my issue is to send that list data to my database table SerialNumber, each method of the lists is a separate field that will fill a database column.
So for example the parse material will fill the database materiallookupcode column and the same for the others.
Here is an image of the database table
Here is the code of all 5 methods that reads the data and then returns it and I need this data send to my database
private List<string> ParseMaterial()
{
var materialList = new List<string>();
foreach (var material in _connection.GetBarcodeList())
{
materialList.Add(material.Substring(10, 5));
}
return materialList;
}
private List<string> ParseLot()
{
var lotList = new List<string>();
var establishmentList = GetEstablishmentCode();
foreach (var lot in _connection.GetBarcodeList())
{
if (establishmentList.Contains("038"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.LoganSport038Property);
}
if (establishmentList.Contains("072"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.LouisaCounty072Property);
}
if (establishmentList.Contains("086"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.Madison086Property);
}
if (establishmentList.Contains("089"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.Perry089Property);
}
if (establishmentList.Contains("069"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.StormLake069Property);
}
if (establishmentList.Contains("088"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.Waterloo088Property);
}
if (establishmentList.Contains("265"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.GoodLetsVille265Property);
}
if (establishmentList.Contains("087"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.CouncilBluffs087Property);
}
if (establishmentList.Contains("064"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.Sherman064Property);
}
}
return lotList;
}
private List<string> ParseSerialNumber()
{
var serialNumberList = new List<string>();
foreach (var serialNumber in _connection.GetBarcodeList())
{
serialNumberList.Add(serialNumber.Substring(36, 10));
}
return serialNumberList;
}
public List<string> ParseNetWeight()
{
var netWeightList = new List<string>();
foreach (var netWeight in _connection.GetBarcodeList())
{
netWeightList.Add(netWeight.Substring(22, 4));
}
return netWeightList;
}
public List<string> ParseGrossWeight()
{
var grossWeightList = new List<string>();
foreach (var grossWeight in _connection.GetBarcodeList())
{
grossWeightList.Add(grossWeight.Substring(22, 4));
}
return grossWeightList;
}
public List<string> FullBarcode()
{
var receiveFullBarcodeList = new List<string>();
foreach (var fullBarcode in _connection.GetBarcodeList())
{
receiveFullBarcodeList.Add(fullBarcode);
}
return receiveFullBarcodeList;
}
public List<string> GetEstablishmentCode()
{
var establishmentList = new List<string>();
foreach (var establishmentCode in _connection.GetBarcodeList())
{
establishmentList.Add(establishmentCode.Substring(36, 3));
}
return establishmentList;
}
The issue is here the button when clicking will read all 5 methods and send it to the database, I am sure the part where I making the list of variables to a string and the separator part is wrong so I need how is the correct way to add those list to each column of the database
private async void btn_SubmitData_Click(object sender, EventArgs e)
{
// parse list methodss
var materialList = ParseMaterial();
var lotList = ParseLot();
var netWeightList = ParseNetWeight();
var grossWeightList = ParseGrossWeight();
var serialNumberList = ParseSerialNumber();
var fullSerialNumberList = FullBarcode();
var material = "";
var lot = "";
var net = "";
var gross = "";
var serial = "";
var fullSerial = "";
var currentUser = _currentUser.GetCurrentUsernameOnApp();
var licensePlateId = GetLicensePlateIds();
for (var i = 0; i < _connection.GetBarcodeList().Count; i++)
{
material = materialList[i];
lot = lotList[i];
net = netWeightList[i];
gross = grossWeightList[i];
serial = serialNumberList[i];
fullSerial = fullSerialNumberList[i];
}
// database table and columns
var serialNumbersInsert = new List<SerialNumber>
{
new SerialNumber
{
SerialNumberLookupCode = serial,
NetWeight = Convert.ToDecimal(net) / 100,
GrossWeight = Convert.ToDecimal(gross) / 100,
LotLookupCode = lot,
MaterialLookupCode = material,
FullSerialNumberLookupCode = fullSerial,
CreatedSysDateTime = DateTime.Now,
ModifiedSysDateTime = DateTime.Now,
CreatedSysUser = currentUser,
ModifiedSysUser = currentUser,
LicensePlateId = licensePlateId
}
};
// insert to the database
foreach (var list in serialNumbersInsert)
{
_unitOfWork.SerialNumbers.Add(list);
}
await _unitOfWork.Complete();
}
Here is the SerialNumber domain class that represents a database table using a code first migration
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BarcodeReceivingApp.Core.Domain
{
// domain class, represents a database table in sql server using code
// first migration
public class SerialNumber
{
public int Id { get; set; }
public int LicensePlateId { get; set; }
public string FullSerialNumberLookupCode { get; set; }
public string SerialNumberLookupCode { get; set; }
public decimal NetWeight { get; set; }
public decimal GrossWeight { get; set; }
public string LotLookupCode { get; set; }
public string MaterialLookupCode { get; set; }
public DateTime CreatedSysDateTime { get; set; }
public DateTime ModifiedSysDateTime { get; set; }
public string CreatedSysUser { get; set; }
public string ModifiedSysUser { get; set; }
}
}
I search other places but could not find a good solution so far, so any help is appreciate it.
I was able to resolve my question, what I did is to assign all lists in a loop and then assign them to each column in the database.
But I am still searching for a better and more clean way to this solution
private async void btn_SubmitData_Click(object sender, EventArgs e)
{
// parse list methods - represents each field of the database column
var materialList = ParseMaterial();
var lotList = ParseLot();
var netWeightList = ParseNetWeight();
var grossWeightList = ParseGrossWeight();
var serialNumberList = ParseSerialNumber();
var fullSerialNumberList = FullBarcode();
var currentUser = _currentUser.GetCurrentUsernameOnApp();
var licensePlateId = GetLicensePlateIds();
for (var i = 0; i < _connection.GetBarcodeList().Count; i++)
{
var serialNumbersInsert = new List<SerialNumber>
{
new SerialNumber
{
SerialNumberLookupCode = materialList[i],
NetWeight = Convert.ToDecimal(netWeightList[i]) / 100,
GrossWeight = Convert.ToDecimal(grossWeightList[i]) / 100,
LotLookupCode = lotList[i],
MaterialLookupCode = materialList[i],
FullSerialNumberLookupCode = fullSerialNumberList[i],
CreatedSysDateTime = DateTime.Now,
ModifiedSysDateTime = DateTime.Now,
CreatedSysUser = currentUser,
ModifiedSysUser = currentUser,
LicensePlateId = licensePlateId
}
};
foreach (var list in serialNumbersInsert)
{
_unitOfWork.SerialNumbers.Add(list);
}
await _unitOfWork.Complete();
}
}

How to create a TreeView from a list of objects in WPF

I have a list of objects that refers the ID, Name and ParentID. I tried to create the treeview. But it is not displaying anything. Could you please help me to create a treeView.I am sharing the code below.
public class WorkFlowScriptIDDataStore
{
public string Id;
public string Name;
public string ParentId;
public List<WorkFlowScriptIDDataStore> Subcategories;
public void Clear()
{
Id = "";
Name = "";
ParentId = "";
}
}
private void PopulateTreeView()
{
List<WorkFlowScriptIDDataStore> localstore = new List<WorkFlowScriptIDDataStore>();
List<WorkFlowScriptIDDataStore> WorkFlowScriptIDDataList = new List<WorkFlowScriptIDDataStore>();
WorkFlowScriptIDDataList.Clear();
int i = 0;
foreach (string node in CurrentScriptids)
{
WorkFlowScriptIDDataList.Add(new WorkFlowScriptIDDataStore());
if (node.Contains(StatusCodes.TAC_TXT_SCENARIOINDEX))
{
datamgm = new TestScenarioConfigurationManager(LayoutConfigurationManager.GetInstance());
WorkFlowScriptIDDataList[i].Id = node;
WorkFlowScriptIDDataList[i].Name = datamgm.GetValue(node, "Name");
WorkFlowScriptIDDataList[i].ParentId = sessionmgm.ScriptID;
}
else if (node.Contains(StatusCodes.TAC_TXT_SEQUENCEINDEX))
{
datamgm = new TestSequenceConfigurationManager(LayoutConfigurationManager.GetInstance());
WorkFlowScriptIDDataList[i].Id = node;
WorkFlowScriptIDDataList[i].Name = datamgm.GetValue(node, "Name");
WorkFlowScriptIDDataList[i].ParentId = sessionmgm.ScriptID;
}
else if (node.Contains(StatusCodes.TAC_TXT_CASEINDEX))
{
datamgm = new TestCaseConfigurationManager(LayoutConfigurationManager.GetInstance());
WorkFlowScriptIDDataList[i].Id = node;
WorkFlowScriptIDDataList[i].Name = datamgm.GetValue(node, "Name");
WorkFlowScriptIDDataList[i].ParentId = sessionmgm.ScriptID;
}
else
{
datamgm = new TestStepConfigurationManager(LayoutConfigurationManager.GetInstance());
WorkFlowScriptIDDataList[i].Id = node;
WorkFlowScriptIDDataList[i].Name = datamgm.GetValue(node, "Name");
WorkFlowScriptIDDataList[i].ParentId = sessionmgm.ScriptID;
}
i++;
}
foreach (var item in WorkFlowScriptIDDataList)
{
localstore.Add(item);
}
while (StartWithTreeviewItem(localstore).Count > 0)
{
GetTreeviewItems(ref localstore);
}
//Creation -TreeView
IEnumerable<WorkFlowScriptIDDataStore> data = WorkFlowScriptIDDataList;
var lookup = data.ToLookup(foo => foo.ParentId,
foo => new TreeItem<object>() { Item = foo });
foreach (var node in lookup.SelectMany(x => x))
node.Children = lookup[((WorkFlowScriptIDDataStore)(node.Item)).Name];
var rootNodes = lookup[null];
treeView.ItemsSource = rootNodes;
}
private List<WorkFlowScriptIDDataStore> StartWithTreeviewItem(List<WorkFlowScriptIDDataStore> lst)
{
return lst.Where(item => item.Id.StartsWith("TSC") ||
item.Id.StartsWith("TSQ") || item.Id.StartsWith("TC")).ToList();
}
private void GetTreeviewItems(ref List<WorkFlowScriptIDDataStore> nodeList)
{
List<string> tempIDList = new List<string>();
List<string> tempPrereqList = new List<string>();
string currentID = string.Empty;
List<WorkFlowScriptIDDataStore> tempstore = new List<WorkFlowScriptIDDataStore>();
configdoc = XDocument.Load(FilePaths.appWorkflowPath + "Workflow" + ".xml");
for (int i = 0; i <= nodeList.Count; i++)
{
if (nodeList.Count > i)
{
if (nodeList.Count > 0)
{
if (nodeList[i].Id.StartsWith("TSC") ||
nodeList[i].Id.StartsWith("TSQ") || nodeList[i].Id.StartsWith("TC"))
{
foreach (XElement xe in configdoc.Descendants("TAWorkFlow"))
{
if (nodeList[i].Id == xe.Element("UniqueID").Value)
{
tempIDList = xe.Element("ScriptID").Value.Split(new char[] { ',' },
StringSplitOptions.RemoveEmptyEntries).ToList<string>();
tempPrereqList = xe.Element("Prerequisite").Value.Split(new char[] { ',' },
StringSplitOptions.RemoveEmptyEntries).ToList<string>();
break;
}
}
currentID = nodeList[i].Id;
tempIDList.Reverse();
tempPrereqList.Reverse();
int k = 0;
tempstore.Clear();
nodeList.RemoveAt(i);
foreach (string id in tempIDList)
{
tempstore.Add(new WorkFlowScriptIDDataStore());
tempstore[k].Id = id;
tempstore[k].Name = tempPrereqList[k];
tempstore[k].ParentId = currentID;
int j = i;
WorkFlowScriptIDDataList.Insert(j + 1, tempstore[k]);
nodeList.Insert(j, tempstore[k]);
j++;
k++;
}
}
}
}
}
}
You need to use properties instead of variables in the WorkFlowScriptIDDataStore class.Try the below sample.
<TreeView x:Name="treeView">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:WorkFlowScriptIDDataStore}" ItemsSource="{Binding Subcategories}">
<TextBlock Text="{Binding Name}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
WorkFlowScriptIDDataStore workFlowScriptIdDataStore = new WorkFlowScriptIDDataStore()
{
Id="1",
Name = "Name",
ParentId = "-1",
Subcategories = new List<WorkFlowScriptIDDataStore>()
{
new WorkFlowScriptIDDataStore()
{
Id="1",
Name = "Name23",
ParentId = "-1",
},
new WorkFlowScriptIDDataStore()
{
Id="2",
Name = "Name1",
ParentId = "-1",
},
}
};
List<WorkFlowScriptIDDataStore> lst = new List<WorkFlowScriptIDDataStore>() { workFlowScriptIdDataStore };
treeView.ItemsSource = lst;
}
}
public class WorkFlowScriptIDDataStore
{
public string Id { get; set; }
public string Name { get; set; }
public string ParentId { get; set; }
public List<WorkFlowScriptIDDataStore> Subcategories { get; set; }
public void Clear()
{
Id = "";
Name = "";
ParentId = "";
}
}

Unable to populate a DataGridViewComboBoxColumn created at design time

I have a DataGridViewComboBoxColumn being craeted at design time.But I want to polulate it at runtime. But it is not happening.
Here is the entire code
public partial class Form1 : Form
{
private List<FileInformation> FileInformationList;
public Form1()
{
InitializeComponent();
PrepareGrid();
DisplayResult();
}
private void PrepareGrid()
{
var fileNameColumn = new DataGridViewTextBoxColumn
{
Name = #"FileName",
HeaderText = "File Name",
DataPropertyName = #"FileName",
AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill,
ReadOnly = false,
Frozen = false
};
dataGridView1.Columns.Add(fileNameColumn);
var downloadColumn = new DataGridViewLinkColumn
{
Name = #"Download",
HeaderText = #"Download",
DataPropertyName = #"Download",
AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill,
ReadOnly = true
};
dataGridView1.Columns.Add(downloadColumn);
var dropdownColumn = new DataGridViewComboBoxColumn
{
Name = #"Test",
HeaderText = #"Country",
AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill,
ReadOnly = true
};
dataGridView1.Columns.Add(dropdownColumn);
}
private void DisplayResult()
{
FileInformationList = LoadItems();
dataGridView1.DataSource = FileInformationList;
((DataGridViewComboBoxColumn)dataGridView1.Columns["Test"]).DataSource = GetCountryList();
((DataGridViewComboBoxColumn)dataGridView1.Columns["Test"]).ValueMember = "id";
((DataGridViewComboBoxColumn)dataGridView1.Columns["Test"]).DisplayMember = "Name";
}
private List<FileInformation> LoadItems()
{
var lstScriptInfo = new List<FileInformation>();
for (int i = 1; i <= 5; i++)
{
lstScriptInfo.Add(new FileInformation { FileName = "File" + i.ToString() + ".txt" });
}
return lstScriptInfo;
}
private DataTable GetCountryList()
{
DataTable CountryDt = new DataTable();
CountryDt.Columns.Add("id");
CountryDt.Columns.Add("Name");
CountryDt.Rows.Add("1", "Canada");
CountryDt.Rows.Add("2", "USA");
return CountryDt;
}
}
public class FileInformation
{
public string FileName { get; set; }
public string Download { get { return "Download File"; } }
}
}
The output is
Please help me to identity what has went wrong?
Two ways to achieve that:
Setting defualt null value for column (skipped null checks):
var cbColumn = (DataGridViewComboBoxColumn)dataGridView1.Columns["Test"];
var ds = GetCountryList();
cbColumn.DataSource = ds;
cbColumn.ValueMember = "id";
cbColumn.DisplayMember = "Name";
cbColumn.DefaultCellStyle.NullValue = ds.Rows[0][0];
cbColumn.DefaultCellStyle.DataSourceNullValue = ds.Rows[0][1];
Second is to iterate after DataBinding and set it manually:
private void DataGridDataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
var hasValue = row.Cells["Test"].Value != null;
if (!hasValue)
{
row.Cells["Test"].Value = 1;
}
}
}
also I'd change binding order:
private void DisplayResult()
{
var cbColumn = (DataGridViewComboBoxColumn)dataGridView1.Columns["Test"];
var ds = GetCountryList();
cbColumn.DataSource = ds;
cbColumn.ValueMember = "id";
cbColumn.DisplayMember = "Name";
cbColumn.DefaultCellStyle.NullValue = ds.Rows[0][0];
cbColumn.DefaultCellStyle.DataSourceNullValue = ds.Rows[0][1];
FileInformationList = LoadItems();
dataGridView1.DataSource = FileInformationList;
}

Resources