Salman Mushtaq Salman Mushtaq - 8 months ago 63
C# Question

How to use Data Binding Linq to SQL to add custom fields

I am developing a windows forms application. I use DataGridView and data binding with LINQ to SQL. It's working. It binds the whole data.

I need some fields instead of whole table data, for example:

The Customers table contains five fields (name, address, mobile, email, age).

I use the code below to get whole data.

private void AssignLocation_Load(object sender, EventArgs e)
{
// Get Datacontext object to connect with data source
SmartxBillingSystemDataContext dc = new SmartxBillingSystemDataContext();

// create table object
Customer customer = new Customer();
var allcustomers = from c in dc.GetTable<Customer>() select c;

// bind to datagrid
customerBindingSource.DataSource = allcustomers;

// now assign binding source to data grid view
dataGridView1.DataSource = customerBindingSource;

}


Now I just need some fields, e.g. Name and Address.

Additionally, I need to add a button in each row like so:

| A Name | An Address | Button |
| Another Name | Fake Address | Button |


How can I achieve this? Please help.

Answer Source

You can create your own class:

public class MyCustomer
{
    public string Name { get; set; }
    public string Address { get; set; }
}

and select like this:

var allMycustomers = from c in dc.GetTable<Customer>() select new MyCustomer { Name = c.Name, Address = c.Address };

customerBindingSource.DataSource = allMycustomers;

for button:

DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
btn.HeaderText = "Button";
btn.Text = "Click Me!";
btn.Name = "btn";
dataGridView1.Columns.Add(btn);
btn.UseColumnTextForButtonValue = true;

Update for button click event you can use dataGridView1_CellClick event..

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
     if (e.ColumnIndex == 2)
     {
            MessageBox.Show((e.RowIndex+1)  + "  Row  " + (e.ColumnIndex+1) + "  Column button clicked ");
     }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download