adding data to dataset - c#

I have a dataset created in "visual studio".
when i open for with data grid it fills the data grid and i can see the data i have entered.
whan loading the form again the data is gone
I have used this code to create new data row.
foreach (var ticket in esTicket)
{
databaseDataSet1.ES.AddESRow(ticket.esNum, ticket.title, ticket.link, ticket.open, ticket.escalated, ticket.downTime, ticket.startWork, ticket.endWork, ticket.toolID, ticket.toolType, ticket.openedBy);
}
and also:
foreach (var ticket in esTicket)
{
databaseDataSet1.ES.Rows.Add(ticket.esNum, ticket.title, ticket.link, ticket.open, ticket.escalated, ticket.downTime, ticket.startWork, ticket.endWork, ticket.toolID, ticket.toolType, ticket.openedBy);
}
the inserted data just does not show

It seems that your esTicket is a list. If so, I suggest that you could use another way to fill the datagridview without using dataset.
Code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
List<Student> list = new List<Student>();
list.Add(new Student { Age=12,Name="Test1",Title="Hello" });
list.Add(new Student { Age = 13, Name = "Test2", Title = "Hi" });
list.Add(new Student { Age = 15, Name = "Test5", Title = "Greeting" });
dataGridView1.DataSource = list;
}
private void button1_Click(object sender, EventArgs e)
{
List<Student> list = (List<Student>)dataGridView1.DataSource;
list.Add(new Student { Age = 16, Name = "Test6", Title = "Hello1" });
dataGridView1.DataSource = null;
dataGridView1.DataSource = list;
}
}
public class Student
{
public int Age { get; set; }
public string Name { get; set; }
public string Title { get; set; }
}
Result:

Related

Duplicate Result When Trying To Fill Datagridview From Checklistbox With ValueMember And DisplayMember

why this loop Return A Duplicate Result
Duplicate Result When Trying To Fill Datagridview From Checklistbox With ValueMember And DisplayMember
private void btn_ShowDetails_Click(object sender, EventArgs e)
{
for (int i = 0; i < clb_SubItems.Items.Count; i++)
{
if (clb_SubItems.GetItemChecked(i))
{
foreach (var item in clb_SubItems.CheckedItems.OfType<SP_SelectDriverItem_Result>())
{
dgv_BOQItems.Rows.Add(item.SubCostItemID, clb_SubItems.GetItemText(clb_SubItems.Items[i]));
}
}
}
}
You might consider setting up the DataGridView with a preset columns and set the DataSource to a List.
Example
Backing class, ToString will be the DisplayMember of the CheckedListBox.
public class Company
{
public int Id { get; set; }
public string Name { get; set; }
public override string ToString() => Name;
}
Mocked data
public class Mocked
{
public static List<Company> Companies => new List<Company>()
{
new Company() {Id = 1, Name = "A"},
new Company() {Id = 2, Name = "B"},
new Company() {Id = 3, Name = "C"},
new Company() {Id = 4, Name = "D"},
};
}
Extension method to get checked companies in a CheckedListBox
public static class CheckedListBoxExtensions
{
public static List<T> CheckedList<T>(this CheckedListBox source)
=> source.Items.Cast<T>()
.Where((item, index) => source.GetItemChecked(index))
.Select(item => item)
.ToList();
}
Form
One CheckedListBox
One DataGridView with columns setup for Id and Name in Company class
One button to get checked items and add each one if not currently in the DataGridView.
Code
public partial class Form1 : Form
{
private readonly BindingSource bindingSource = new BindingSource();
protected BindingList<Company> bindingList = new BindingList<Company>();
public Form1()
{
InitializeComponent();
dataGridView1.AutoGenerateColumns = false;
}
private void Form1_Load(object sender, EventArgs e)
{
bindingSource.DataSource = bindingList;
dataGridView1.DataSource = bindingSource;
checkedListBox1.DataSource = Mocked.Companies;
}
private void PopulateGridButton_Click(object sender, EventArgs e)
{
var result = checkedListBox1.CheckedList<Company>();
if (result.Count <= 0) return;
foreach (var company in result)
{
if (!bindingList.Contains(company))
{
bindingList.Add(company);
}
}
}
}

How to bind nested list to datagridview in winforms

I am creating app in windows form. Below mentioned is structure of my list that I am going to bind to DataGridView. I have main list(Student) and inside main list, I have child list(Book) that is to be bind to DataGrid View. So, main list will have Id(int), Name(string) and lstBk(list which is child list).
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public List<Book> lstBk { get; set; }
}
public class Book
{
public int ID { get; set; }
public string Name{ get; set; }
}
Whenever I bind list to datagrid view, I am getting Id and Name only but not lstBk in grid view row. How do I get lstBk after ID and Name in datagrid view?
List<Book> lst = new List<Book>();
lst.Add(new Book() { ID= 1, Name ="Book 1" } );
lst.Add(new Book() { ID = 2, Name = "Book 2" });
lst.Add(new Book() { ID = 3, Name = "Book 3" });
List<Student> lstUD = new List<Student>();
lstUD.Add(new Student() { ID = 1, Name = "First Name1", lstBk = lst });
lstUD.Add(new Student() { ID = 2, Name = "First Name2", lstBk = lst });
dataGridView1.DataSource = lstUD;
One possible solution is to “flatten” the Book list. If we override the Books ToString method to output the books ID and Name... then we could then add a property to the Student class that creates a single string from all the Books in the list. Something like…
Book Class…
public class Book {
public int ID { get; set; }
public string Name { get; set; }
public override string ToString() {
return ID + " - " + Name;
}
}
Then create a new string property ListOfBooks in the Student Class. This will get shown in the grid. Something like...
public class Student {
public int ID { get; set; }
public string Name { get; set; }
public List<Book> lstBk { get; set; }
public string ListOfBooks {
get {
return string.Join(", ", lstBk);
}
}
}
This will put all the books from the list into a single cell in the grid. If there is too much data in the cell, then I would suggest using a master-detail with two grids. One for the student and another to display the books from the “selected” student in the “student/Master” grid.
Using a Master-Detail with two grids.
Create a new winforms project, drop a couple of DataGridViews onto the form and the code below should demonstrate one way to implement a Master-Detail using the classes you have posted.
In this case, the Book ToString override is obviously not needed in addition to the added ListOfBooks property in the Student class. They may look like the original post…
public class Book {
public int ID { get; set; }
public string Name { get; set; }
}
public class Student {
public int ID { get; set; }
public string Name { get; set; }
public List<Book> lstBk { get; set; }
}
We will need some mechanism to “signal” when the user “selects” a different cell in the “Student/Master” grid. For this, we will wire up the grids SelectionChanged event. In that event, the code "cast" the selected Student in the grid to a Student object, then uses the Students lstBk list to display into the “Book/Details” grid. This event may look something like below…
private void dataGridView1_SelectionChanged(object sender, EventArgs e) {
Student student = (Student)dataGridView1.CurrentRow.DataBoundItem;
dataGridView2.DataSource = student.lstBk;
}
When the grids are loaded, the details grid is filled using the first row in the master grid as in most cases, this is the default selected cell.
To complete this example, 10 Students are added to the “Student/Master” grid such that each student has a random number of books between 1 and 6.
List<Student> AllStudents;
Random rand;
public Form1() {
InitializeComponent();
dataGridView1.SelectionChanged += new EventHandler(dataGridView1_SelectionChanged);
AllStudents = new List<Student>();
rand = new Random();
}
private void Form1_Load(object sender, EventArgs e) {
for (int i = 1; i < 11; i++) {
AllStudents.Add(GetStudent(i, "Student_" + i + 1));
}
dataGridView1.DataSource = AllStudents;
dataGridView2.DataSource = AllStudents[0].lstBk;
}
private Student GetStudent(int studentID, string name) {
int numberOfBooks = rand.Next(1, 7);
int bookNumber;
List<Book> books = new List<Book>();
for (int i = 0; i < numberOfBooks; i++) {
bookNumber = rand.Next(1, 10000);
books.Add(new Book { ID = bookNumber, Name = "Book" + bookNumber });
}
return new Student { ID = studentID, Name = name, lstBk = books };
}
I hope this makes sense.

How to load Object type data in ListView visual studio

I have a query to load users from Parse server and put them in a list view
But after loading the users i cant add them to the list, In short what i need to do is put a list of Objects type data in a list view
So what should i do
My Code:
private async Task<IEnumerable<Users>> GetUsersListAsync()
{
var List = new List<Users>();
var query = ParseUser.Query;
IEnumerable<ParseUser> results = await query.FindAsync();
results.ToList();
}
Users class:
public class Users
{
public Users()
{
}
public string Id{get; set;}
public string Name { get; set; }
public string Number { get; set; }
}
Do you want to load the data in the list into the ListView? If so, please refer to the following code.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// Set the view of ListView
listView.View = View.Details;
// Add columns
listView.Columns.Add("Id", 120, HorizontalAlignment.Left);
listView.Columns.Add("Name", 120, HorizontalAlignment.Left);
listView.Columns.Add("Number", 120, HorizontalAlignment.Left);
}
private void btnLoad_Click(object sender, EventArgs e)
{
// Simulated data
List<Users> users = new List<Users>() {
new Users { Id = "1", Name = "A", Number = "10"},
new Users { Id = "2", Name = "B", Number = "20"},
new Users { Id = "3", Name = "C", Number = "30"},
new Users { Id = "4", Name = "D", Number = "40"},
new Users { Id = "5", Name = "E", Number = "50"},
};
listView.BeginUpdate();
foreach (var user in users)
{
// Add new listview items
ListViewItem lvi = new ListViewItem();
lvi.Text = user.Id;
lvi.SubItems.Add(user.Name);
lvi.SubItems.Add(user.Number);
listView.Items.Add(lvi);
}
listView.EndUpdate();
}
}
public class Users
{
public Users()
{
}
public string Id { get; set; }
public string Name { get; set; }
public string Number { get; set; }
}

Issue on Rendering List in Grid in C#

I am trying to render a simple List into a Grid like
var sr = new BindingSource();
sr.DataSource = str;
dataGridView1.DataSource = sr;
I am not getting any error but not able to display the list in Grid. Here is the entire code
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Enum
{
public enum Sex {Male, Female, Other };
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
List<Sex> str = new List<Sex>();
str.Add(Sex.Female);
str.Add(Sex.Male);
var sr = new BindingSource();
sr.DataSource = str;
dataGridView1.DataSource = sr;
}
}
}
DataGridView cannot bind to a list of primitive values (like int, decimal, DateTime, enum, string etc.) because it requires a list containing objects with properties.
The easiest way is to use LINQ projection to an anonymous type with single property like this (BindingSource is not needed at all):
private void button1_Click(object sender, EventArgs e)
{
List<Sex> str = new List<Sex>();
str.Add(Sex.Female);
str.Add(Sex.Male);
dataGridView1.DataSource = str.Select(value => new { Sex = value }).ToList();
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public class Person
{
public string Name { get; set; }
public string Lastname { get; set; }
public Sex Sex { get; set; }
}
public enum Sex { Male, Female, Other };
private void button1_Click(object sender, EventArgs e)
{
BindingList<Person> persons = new BindingList<Person>();
persons.Add(new Person() { Name = "Joe", Lastname = "Doe" , Sex = Sex.Male});
persons.Add(new Person() { Name = "Nancy", Lastname = "Foo" , Sex = Sex.Female});
dataGridView1.DataSource = persons;
}
}
I don't think you can bind an enum to GridView. This is what I could get working
public class Person
{
public Sex Gender { get; set; }
}
You need to use BindingList as list does not implement IBindingList
var list = new List<Person>()
{
new Person { Gender = Sex.Male, },
new Person { Gender = Sex.Female, },
};
var bindingList = new BindingList<Person>(list);
var source = new BindingSource(bindingList, null);
dataGridView1.DataSource = source;

wpf get value by name?

on WPF on c# i have combobox
<ComboBox x:Name="listCombobox" />
and i add it item like
var list = new[]
{
new { Number = 1, Name = "Smith" },
new { Number = 12, Name = "John" } ,
new { Number = 14, Name = "Bon" }
}.ToList();
foreach (var item in list)
{
listCombobox.Items.Add(item.Name);
}
what i want that on the combobox i will see the Name(like now)
but when i selected , on the code behind i will see not the name i selected
i want to see the Number that selected
thanks!
Define a class like this
public class dataObject
{
public int Number { get; set; }
public string Name { get; set; }
}
And fill the data,
List<dataObject> bindingList = new List<dataObject>();
bindingList.Add(new dataObject()
{
Name = "Smith",
Number = 1
});
bindingList.Add(new dataObject()
{
Name = "John",
Number = 12
});
bindingList.Add(new dataObject()
{
Name = "Bon",
Number = 14
});
listCombobox.ItemsSource = bindingList;
listCombobox.DisplayMemberPath = "Name";
On selectionChanged event of the combobox, do this,
private void listCombobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
dataObject result = (dataObject)listCombobox.SelectedItem;
var selectedNumber = result.Number;
}
I would use a custom ListItem class and assign objects of this type to the ItemSource property of the combobox control like this:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var list = new List<ListItem>
{
new ListItem{ Value = 1, Text = "Smith" },
new ListItem{ Value = 12, Text = "John" } ,
new ListItem{ Value = 14, Text = "Bon" }
}.ToList();
listCombobox.ItemsSource = list;
listCombobox.DisplayMemberPath = "Text";
listCombobox.SelectedValuePath = "Value";
}
private void listCombobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selectedItem = (sender as ComboBox).SelectedItem as ListItem;
if (selectedItem != null)
{
// do something with the selected item
}
}
}
public class ListItem
{
public string Text { get; set; }
public int Value { get; set; }
}
I would solve it as follows:
...
foreach (var item in list)
listCombobox.Items.Add(new ComboBoxItem() {
Content = item.Name,
Tag = item.Number
});
You can of course retrieve your Data by using
int mytag = listCombobox.Items[3].Tag;
or
int seletected = listCombobox.SelectedItem.Tag;
MSDN Reference for PresentationFramework.dll::System.Windows.Frameworkelement.Tag
Easiest way, I think, is to put these numbers as Tag of every listCombobox item:
foreach (var item in list) {
listCombobox.Items.Add(new ComboBoxItem { Content = item.Name, Tag = item.Number });
}
And access your number (OnSelectedItemchanged, for example):
void Cb_SelectionChanged(object sender, SelectionChangedEventArgs e) {
int number = (int)((ComboBoxItem) listCombobox.SelectedItem).Tag;
}

Categories

Resources