【问题标题】:How to use Data Binding Linq to SQL to add custom fields如何使用 Data Binding Linq to SQL 添加自定义字段
【发布时间】:2018-01-25 19:39:19
【问题描述】:

我正在开发一个 Windows 窗体应用程序。我将 DataGridView 和数据绑定与 LINQ to SQL 一起使用。它正在工作。它绑定了整个数据。

我需要一些字段而不是整表数据,例如:

客户表包含五个字段(姓名、地址、手机、电子邮件、年龄)。

我使用下面的代码来获取整个数据。

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;

}    

现在我只需要一些字段,例如姓名和地址。

另外,我需要在每一行中添加一个按钮,如下所示:

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

我怎样才能做到这一点?请帮忙。

对于点击事件,我使用下面的代码

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            popUpLocationWindow();
        }

        private void popUpLocationWindow()
        {
            MessageBox.Show("I am clicked");
        }

但是这段代码不起作用。

【问题讨论】:

  • @mjwills,我是开发新手,不了解提供的链接。能否请您给我一些与我的场景相关的想法,以便我消化。
  • 您必须将一个一个数据成员添加到您想要的网格视图中 datafieldname 应该与对象属性相同,以便将额外字段与按钮类型绑定以获得额外的列.

标签: c# linq datagridview


【解决方案1】:

您可以创建自己的类:

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

然后像这样选择:

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

customerBindingSource.DataSource = allMycustomers;

对于按钮:

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

更新按钮点击事件你可以使用dataGridView1_CellClick事件..

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
     if (e.ColumnIndex == 2)
     {
            MessageBox.Show((e.RowIndex+1)  + "  Row  " + (e.ColumnIndex+1) + "  Column button clicked ");
     }
}

【讨论】:

  • 亲爱的蚕儿,感谢您的帮助。是的,它的工作原理。还有一件事。如果我需要在按钮上制作方法,请点击我该怎么做?
  • 感谢您的回复和方法。在我用按钮分配此方法的地方使用您的代码。表示没有 OnClick 方法。
  • @SalmanMushtaq 抱歉没有 :( 您可以使用视图单元格单击事件来处理它...
  • @SalmanMushtaq dataGridView1.CellClick += dataGridView1_CellClick; 你的点击事件定义了吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-16
相关资源
最近更新 更多