我正在尝试在DataGridView中显示我的一个数据库表。我使用EF Code First方法创建了数据库。这是我的DB类:
public class BloodDonor
{
public int BloodDonorId { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
public DateTime DateofBirth { get; set; }
public DateTime DateOfRegistration { get; set; }
public BloodTypes BloodType { get; set; }
public virtual List<BloodDonation> BloodDonations { get; set; }
}
public class BloodDonation
{
public int BloodDonationId { get; set; }
public DateTime DateOfDonation { get; set; }
public virtual BloodDonor bloodDonor { get; set; }
}
public class BloodBankContext: DbContext
{
public BloodBankContext() : base("BloodBankDatabase1")
{
Database.SetInitializer<BloodBankContext>(new DropCreateDatabaseAlways<BloodBankContext>());
}
public DbSet<BloodDonor> BloodDonors { get; set; }
public DbSet<BloodDonation> BloodDonations { get; set; }
}
这是我的主要表格:
public partial class BloodBankManager : Form
{
public static BloodBankContext context;
public BloodBankManager()
{
InitializeComponent();
context = new BloodBankContext();
ExampleDataFiller exampleDataFiller = new ExampleDataFiller(context);
var query = from b in context.BloodDonors
select b;
foreach (var donor in query)
{
MessageBox.Show(donor.BloodDonorId + " " + donor.FirstName + " " + donor.LastName + " " + donor.DateofBirth.ToShortDateString() + " " + donor.BloodType);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void newBloodDonorButton_Click(object sender, EventArgs e)
{
NewBloodDonorForm newBloodDonorForm = new NewBloodDonorForm();
newBloodDonorForm.bloodBankManager = this;
newBloodDonorForm.Show();
}
}
我的数据库似乎工作正常,但我不知道如何显示
context.BloodDonors
DataGridView中的。我尝试在DataGridViewProperty中使用DataSource向导,但在我第一次运行应用程序后,DataGridView在更改BloodDonors表后不会更新。有关将所需表附加到DataGridView的最简单方法的想法吗?
答案 0 :(得分:0)
您需要绑定到DataGridView.DataSource
属性。
在这里阅读更多内容 http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.datasource(v=vs.110).aspx
这是一个代码示例
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
string sql = "SELECT * FROM Authors";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Authors_table");
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Authors_table";
}
}
}
以下是另一个链接,其中包含有关binding
的更多信息