create a form with some searchable demo data in a table in csharp

To create a form with a searchable demo data in a table in C#, you can follow these steps:

  1. Create a new Windows Forms Application project in Visual Studio
  2. Drag a DataGridView control from the toolbox to the form design surface
  3. Set the DataGridView properties, such as DataSource and AutoGenerateColumns, to configure the table layout and binding
  4. Create a sample data source, such as a DataTable or List, to populate the table with some demo data
  5. Implement a search functionality by adding a TextBox control and a Button control, and handle the Button.Click event to filter the data based on the search criteria
  6. Update the DataGridView.DataSource property with the filtered data to refresh the table display

Here's a sample code snippet that demonstrates this approach:

main.cs
// Create a sample data source (a list of Person objects)
List<Person> persons = new List<Person>();
persons.Add(new Person("John", "Doe", "123 Main St.", "Boston"));
persons.Add(new Person("Jane", "Smith", "456 Oak St.", "New York"));
persons.Add(new Person("Bob", "Johnson", "789 Elm St.", "Chicago"));

// Set up the DataGridView control
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = persons;

// Handle the search button click event
private void btnSearch_Click(object sender, EventArgs e)
{
    string keyword = txtSearch.Text.ToLower();
    var filteredData = persons.Where(p => p.FirstName.ToLower().Contains(keyword) 
                                          || p.LastName.ToLower().Contains(keyword)
                                          || p.Address.ToLower().Contains(keyword)
                                          || p.City.ToLower().Contains(keyword));
    dataGridView1.DataSource = filteredData.ToList();
}

// Person class for data modeling
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public string City { get; set; }

    public Person(string firstName, string lastName, string address, string city)
    {
        FirstName = firstName;
        LastName = lastName;
        Address = address;
        City = city;
    }
}
1376 chars
38 lines

This code creates a new List of Person objects and set it as the data source for the DataGridView control. It also defines a search button click event handler that filters the data based on the search keyword entered in the TextBox control. Finally, it updates the DataGridView.DataSource property with the filtered data to show the search results in the table.

gistlibby LogSnag