I have following class
public class ComboData
{
public int Id { get; set;}
public string Value { get; set;}
public string description { get; set;}
}
I'm binding data to combo box like following
List<ComboData> ListData = new List<ComboData>();
ListData.Add(new ComboData { Id = "1", Value = "One" });
ListData.Add(new ComboData { Id = "2", Value = "Two" });
ListData.Add(new ComboData { Id = "3", Value = "Three" });
ListData.Add(new ComboData { Id = "4", Value = "Four" });
ListData.Add(new ComboData { Id = "5", Value = "Five" });
cbotest.ItemsSource = ListData;
cbotest.DisplayMemberPath = "Value";
cbotest.SelectedValuePath = "Id";
cbotest.SelectedValue = "2";
now I changed my code to get above hard coded values from following Entity Framework GetAll method
public class DAL
{
Dbcontext db = new Dbcontext();
public List<ComboData> GetAll()
{
var sp = db.ComboDatas.ToList();
return sp;
}
}
How can I bind this values to above cbotest.ItemsSource directly with Id and Value ?
It will be, just assign the function to the ItemsSource which will return a List of ComboData
cbotest.ItemsSource = GetAll();
cbotest.DisplayMemberPath = "Value";
cbotest.SelectedValuePath = "Id";
cbotest.SelectedValue = "2";
Related
I need some help. I have written code in MVC 5 .NET Framework where I used session to store my cart items list. It was pretty straight forward but now I am rewriting the code in ASP.NET MVC CORE 6 for another project but it is not working the way I was expecting.
Scenario:
I have a List of items as below:
private List<SalesCartItemsModel>? itemsList; //Shopping Cart
public SalesController()
{
itemsList = new List<SalesCartItemsModel>();
}
I want to use Session to store my Cart Items. I used this simple syntax:
Session["cartItems"] = null;
if (Session["cartItems"] != null)
{
itemsList = (List<PurchaseCartItem>)Session["cartItems"];
}
Session["cartItems"] = itemsList;
Now when i try to use the same in MVC CORE 6, it seems it doesnt support this syntax anymore. What i have tried so far is
HttpContext.Session.SetString("cartItems", itemsList)
But it throws error and does not accept it.
ERROR:
cannot convert from
'System.Collections.Generic.List<.Models.SalesCart.SalesCartItemsModel>'
to 'string'
Please help me how can I achieve the same in MVC Core? How can I change the code in the current syntax to MVC CORE 6.0?
Maybe this is what you want to know:
Models:
public class SalesCartItemsModel
{
public string ShopId { get; set; }
public string ShopName { get; set; }
}
public class PurchaseCartItem
{
public string ShopId { get; set; }
public string ShopName { get; set; }
}
SessionExtensions:
public static class SessionExtensions
{
public static void Set<T>(this ISession session, string key, T value)
{
session.SetString(key, JsonSerializer.Serialize(value));
}
public static T Get<T>(this ISession session, string key)
{
var value = session.GetString(key);
return value == null ? default : JsonSerializer.Deserialize<T>(value);
}
}
Program:
builder.Services.AddSession();
app.UseSession();
Controller:
private List<SalesCartItemsModel>? itemsList;
private List<PurchaseCartItem>? itemListP;
public JsonResult Test()
{
itemsList = new List<SalesCartItemsModel>();
itemsList.Add(new SalesCartItemsModel { ShopId = "1", ShopName = "Apple" });
itemsList.Add(new SalesCartItemsModel { ShopId = "2", ShopName = "Banana" });
HttpContext.Session.Set<List<SalesCartItemsModel>>("cartItems", itemsList);
var value = HttpContext.Session.Get<List<SalesCartItemsModel>>("cartItems");
return Json(value);
}
Result:
When you don't store the value in the session, you can judge value=null to store the new value for the session:
public JsonResult Test()
{
itemsList = new List<SalesCartItemsModel>();
//itemsList.Add(new SalesCartItemsModel { ShopId = "1", ShopName = "Apple" });
//itemsList.Add(new SalesCartItemsModel { ShopId = "2", ShopName = "Banana" });
//HttpContext.Session.Set<List<SalesCartItemsModel>>("cartItems", itemsList);
var value = HttpContext.Session.Get<List<SalesCartItemsModel>>("cartItems");
if (value == null)
{
itemListP = new List<PurchaseCartItem>();
itemListP.Add(new PurchaseCartItem { ShopId = "1", ShopName = "Orange" });
itemListP.Add(new PurchaseCartItem { ShopId = "2", ShopName = "Pear" });
HttpContext.Session.Set<List<PurchaseCartItem>>("cartItems", itemListP);
var valueP = HttpContext.Session.Get<List<PurchaseCartItem>>("cartItems");
return Json(valueP);
}
else
{
return Json(value);
}
}
Result:
When there is no value in your itemsList, you can judge value.Count=0 to add a new value to the session:
public JsonResult Test()
{
itemsList = new List<SalesCartItemsModel>();
//itemsList.Add(new SalesCartItemsModel { ShopId = "1", ShopName = "Apple" });
//itemsList.Add(new SalesCartItemsModel { ShopId = "2", ShopName = "Banana" });
HttpContext.Session.Set<List<SalesCartItemsModel>>("cartItems", itemsList);
var value = HttpContext.Session.Get<List<SalesCartItemsModel>>("cartItems");
if (value.Count == 0)
{
itemListP = new List<PurchaseCartItem>();
itemListP.Add(new PurchaseCartItem { ShopId = "1", ShopName = "Orange" });
itemListP.Add(new PurchaseCartItem { ShopId = "2", ShopName = "Pear" });
HttpContext.Session.Set<List<PurchaseCartItem>>("cartItems", itemListP);
var valueP = HttpContext.Session.Get<List<PurchaseCartItem>>("cartItems");
return Json(valueP);
}
else
{
return Json(value);
}
}
Result:
I have the following JSON.
public class Code
{
public string ID { get; set; }
}
public class Country
{
public string CountryID { get; set; }
}
public class Complex
{
public Country Country { get; set; }
public Code Code { get; set; }
public string cText { get; set; }
}
public List<Complex> GetData()
{
List<Complex> Data = new List<Complex>();
Data.Add(new Complex() { Country = new Country() { CountryID = "Australia" }, Code = new Code() { ID = "AU" }, cText = "Australia" });
Data.Add(new Complex() { Country = new Country() { CountryID = "Bermuda" }, Code = new Code() { ID = "BM" }, cText = "Bermuda" });
Data.Add(new Complex() { Country = new Country() { CountryID = "Canada" }, Code = new Code() { ID = "CA" }, cText = "Canada" });
Data.Add(new Complex() { Country = new Country() { CountryID = "France" }, Code = new Code() { ID = "FR" }, cText = "France" });
return Data;
}
I need to get the value of CountryID from the given complex key ("Country.CountryID").
I have tried to get the value using the TryGetValue method in c#. It is doesn't work.
I think I need to split the key and process the Complex JSON and find the nested result.
Could you please suggest how to get the value for the complex object from the given complex key?
It can be done via LINQ like this
var codeIdToFind = "AU";
var result = data.Where(c => c.Code.ID.Equals(codeIdToFind, StringComparison.OrdinalIgnoreCase))
.Select(x => x.Country.CountryID)
.FirstOrDefault();
I am trying to create a dynamic control based in MVC,
I got a solution to implement.. it working fine..
with this code
public class DynamicControlViewModel
{
public ControlViewModel[] Controls { get; set; }
}
public abstract class ControlViewModel
{
public abstract string Type { get; }
public bool Visible { get; set; }
public string Label { get; set; }
public string Name { get; set; }
}
public class TextBoxViewModel : ControlViewModel
{
public override string Type
{
get { return "textbox"; }
}
public string Value { get; set; }
}
public class CheckBoxViewModel : ControlViewModel
{
public override string Type
{
get { return "checkbox"; }
}
public bool Value { get; set; }
}
public class DropDownListViewModel : TextBoxViewModel
{
public override string Type
{
get { return "ddl"; }
}
public SelectList Values { get; set; }
}
This is the way i am calling the object
public ActionResult Index()
{
return View(GetControls1());
}
public DynamicControlViewModel GetControls1()
{
var model1 = new DynamicControlViewModel
{
Controls = new ControlViewModel[] {
new DropDownListViewModel{Visible = true,Label = "drop label",Name = "DropDown1",Values = new SelectList(new[]{new { Value = "1", Text = "text 1" },new { Value = "2", Text = "text 2" },new { Value = "3", Text = "text 3" },}, "Value", "Text", "2")},
new TextBoxViewModel { Visible = true, Label = "label 1", Name = "TextBox1", Value = "value of textbox" },
new CheckBoxViewModel { Visible = true, Label = "CheckBox label 1", Name = "CheckBox1", Value = true},
new TextBoxViewModel { Visible = true, Label = "label 2", Name = "TextBox2", Value = "value of textbox" }}
};
return model1;
}
Here,
I need to use for loop to create the dynamic control..
here is my code, getting error
public DynamicControlViewModel GetControls()
{
var model = new DynamicControlViewModel { };
var Controls1 = new ControlViewModel[] { };
var s = model.Controls;
//int i=0;
//for loop start
Controls1[0] = new TextBoxViewModel { Visible = true, Label = "label 2", Name = "TextBox2", Value = "value of textbox" };
Controls1[1] = new TextBoxViewModel { Visible = true, Label = "label 3", Name = "TextBox3", Value = "value of textbox" };
Controls1[2] = new CheckBoxViewModel { Visible = true, Label = "CheckBox label 1", Name = "CheckBox1", Value = true },
Controls1[3] = new DropDownListViewModel { Visible = true, Label = "drop label", Name = "DropDown1", Values = new SelectList(new[] { new { Value = "1", Text = "text 1" }, new { Value = "2", Text = "text 2" }, new { Value = "3", Text = "text 3" }, }, "Value", "Text", "2") },
//loop end
var model1 = new DynamicControlViewModel
{
Controls = Controls1
};
return model1;
}
The problem is that you first define an array of size 0 (i.e. with 0 cells to hold values):
var Controls1 = new ControlViewModel[] { }; // array with length 0
Afterwards you try to assign to the first, second, third and fourth cell of the array, which do not exist. Therefore you get the error.
So you should either use a List<ControlViewModel> or initialize an array of the correct length:
var Controls1 = new ControlViewModel[4];
List table contains duplicating elements, how to improve this situation and copy data without duplicates in new list employee using linq?
For example output must be something like:
List<Employee> employee = new List<Employee>();
employee.Add(new Employee
{
Name = "Jhon",
components = new List<Component>
{
new Component { id = "4", work = "clear" },
new Component { id = "10", work = "load" },
new Component { id = "5", work = "convert"},
}
});
But how to do it using linq?
Code:
class Program
{
static void Main(string[] args)
{
List<Table> table = new List<Table>();
table.Add(new Table { Name = "Jhon", id = "4", work = "clear" });
table.Add(new Table { Name = "Jhon", id = "10", work = "load" });
table.Add(new Table { Name = "Jhon", id = "5", work = "convert" });
table.Add(new Table { Name = "Nick", id = "2", work = "load" });
table.Add(new Table { Name = "Nick", id = "7", work = "load" });
table.Add(new Table { Name = "Nick", id = "9", work = "load" });
}
}
public class Empoloyee
{
public string Name { get; set; }
public List<Component> components { get; set; }
}
public class Component
{
public string id { get; set; }
public string work { get; set; }
}
public class Table
{
public string Name { get; set; }
public string id { get; set; }
public string work { get; set; }
}
I guess you want have components grouped by employ name
List<Table> table = new List<Table>();
table.Add(new Table { Name = "Jhon", id = "4", work = "clear" });
table.Add(new Table { Name = "Jhon", id = "10", work = "load" });
table.Add(new Table { Name = "Jhon", id = "5", work = "convert" });
table.Add(new Table { Name = "Nick", id = "2", work = "load" });
table.Add(new Table { Name = "Nick", id = "7", work = "load" });
table.Add(new Table { Name = "Nick", id = "9", work = "load" });
var employee = table.GroupBy(t => t.Name)
.Select(g => new Empoloyee() {Name = g.Key, components = g.Select(t => new Component {id = t.id, work = t.work} ).ToList()})
.ToList();
This LINQ statement will generate the output you want:
List<Empoloyee> employee = table
.GroupBy(t => t.Name)
.Select(t => new Empoloyee() {
Name = t.Key,
components = t.Select(s => new Component() {
id = s.id,
work = s.work
})
.ToList()
})
.ToList();
What you need is Grouping on Name.
var results = table.GroupBy(t=>t.Name)
.Select( s=> new Empoloyee() {
Name = s.Key,
components= s.Select(c=> new Component() { id = c.id, work = c.work}).ToList()
}).ToList();
Working Code
I have the following data I want to display in a DataGridView:
DataEntry[] data = new[]{
new DataEntry(){Name = "A", Entries = new []{ "1", "2"}},
new DataEntry(){Name = "B", Entries = new []{ "1", "2", "3"}}};
"Name" will be a simple TextBox field, and "Entries" a ComboBox where the items to choose from are the elements in the list.
So in this example there would be 2 rows (below is what the datagridview would look like):
Name Entries
Row1 : A <choice of "1" or "2">
Row1 : B <choice of "1" or "2" or "3">
My question is, how do I bind this data?! I've looked at the DataPropertyName, DisplayMember and ValueMember properties... but just cannot work this one out.
Below is the code as it stands - with a comment where I need to add the magic couple of lines to set the DataSource etc. for the Entries column.
public partial class Form1 : Form
{
DataEntry[] data = new[]{
new DataEntry(){Name = "A", Entries = new []{ "1", "2"}},
new DataEntry(){Name = "B", Entries = new []{ "1", "2", "3"}}};
public Form1()
{
InitializeComponent();
dataGridView1.AutoGenerateColumns = false;
var nameCol = new DataGridViewTextBoxColumn();
nameCol.DataPropertyName = "Name";
var entriesCol = new DataGridViewComboBoxColumn();
//entriesCol. ???? = "Entries"; !!
dataGridView1.Columns.AddRange(new DataGridViewColumn[] { nameCol, entriesCol });
dataGridView1.DataSource = data;
}
}
public class DataEntry
{
public string Name { get; set; }
public IEnumerable<string> Entries { get; set; }
}
Come in this morning, and within 10 minutes I had it working!
Thanks go to this MSDN forum post
Solution is to subscribe to the "DataBindingComplete" event and to then go through each row and set the data source on each ComboBoxCell. It would be nice to have a more elegant solution - but hey - it works!
Below is a working version of the code sample I submitted in the original question:
public partial class Form1 : Form
{
DataEntry[] data = new[]{
new DataEntry(){Name = "A", Entries = new []{ "1", "2", "3", "4"}},
new DataEntry(){Name = "B", Entries = new []{ "1", "2", "3"}}};
string[] cols = new[] { "col1", "col2" };
public Form1()
{
InitializeComponent();
dataGridView1.AutoGenerateColumns = false;
var nameCol = new DataGridViewTextBoxColumn();
nameCol.DataPropertyName = "Name";
var entriesCol = new DataGridViewComboBoxColumn();
entriesCol.Name = "Entries";
dataGridView1.Columns.AddRange(new DataGridViewColumn[] { nameCol, entriesCol });
dataGridView1.DataSource = data;
dataGridView1.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(dataGridView1_DataBindingComplete);
}
void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
DataGridViewComboBoxCell comboCell = (DataGridViewComboBoxCell)dataGridView1.Rows[i].Cells["Entries"];
DataEntry entry = dataGridView1.Rows[i].DataBoundItem as DataEntry;
comboCell.DataSource = entry.Entries;
comboCell.Value = entry.Entries.First();
}
}
}
public class DataEntry
{
public string Name { get; set; }
public IEnumerable<string> Entries { get; set; }
}
I recently had to do this and found a different solution.
I used 2 BindingSources to get the job done. The first one is used to populate the Datagrid, and the 2nd one uses is used by the ComboBoxColumn and uses the first BindingSource as it's DataSource references a DataMember off it.
Here is a DataObject we might want to bind:
class DataObject
{
public string Name { get; set; }
public string Value { get; set; }
public string [] ValueList { get; set; }
}
The Designer file would look something like:
// dataGridView1
this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.nameDataGridViewTextBoxColumn,
this.valueDataGridViewTextBoxColumn});
this.dataGridView1.DataSource = this.bindingSource1;
// bindingSource1
this.bindingSource1.DataSource = typeof(SomeNamespace.DataObject);
// valueListBindingSource
this.valueListBindingSource.DataMember = "ValueList";
this.valueListBindingSource.DataSource = this.bindingSource1;
// nameDataGridViewTextBoxColumn
this.nameDataGridViewTextBoxColumn.DataPropertyName = "Name";
// valueDataGridViewTextBoxColumn
this.valueDataGridViewTextBoxColumn.DataPropertyName = "Value";
this.valueDataGridViewTextBoxColumn.DataSource = this.valueListBindingSource;
Then a simple Form could look like:
public Form1 ()
{
InitializeComponent ();
m_objects = new List<DataObject> {
new DataObject { Name = "foo", ValueList = new [] { "1", "2", "3", "4" }},
new DataObject { Name = "bar", ValueList = new [] { "a", "b", "c" }}
};
bindingSource1.DataSource = m_objects;
}
private IList<DataObject> m_objects;