我是编程世界和堆栈流的新手,所以请原谅' noob'题... 我在这里有这个方法(链接到窗体),这里的想法是向文本框添加信息,并将它添加到Gridview和数据库。问题是,添加的信息中只有一个部分(自动生成的ID)显示在(ID)上
private void btnAddNewAdmin_Click(object sender, EventArgs e)
{
if (!(txtAdminFname.Text == string.Empty || txtAdminLname.Text == string.Empty ||
txtPassword.Text == string.Empty))
{
MessageBox.Show("ERROR: all the boxes have to be filled and try again.");
}
// Here it will ADD a new Admin based on the information entered in the form, the New ID for the Admin is generated by the program.
try
{
using (Hawthor_HS_Entities db = new Hawthor_HS_Entities())
{
Administrator addAdministrator = new Administrator();// currently adding only the AID and nothing else.
{
addAdministrator.FName = txtAdminFname.Text;
addAdministrator.LName = txtAdminLname.Text;
addAdministrator.Password = txtNewPass.Text;
}
db.Administrators.Add(addAdministrator);
db.SaveChanges();
DataGridLoad();
MessageBox.Show("Success! New Administrator was Added");
}
}
catch (Exception)
{
MessageBox.Show("Error: Could not Add new Administrator. Please try again.");
}
}
我有一个"编辑"一旦创建了该行(仅使用ID),这个方法似乎工作得很好。 我感谢任何帮助...提前感谢
继承DataGridLoad()
private void DataGridLoad()
{
using (Hawthor_HS_Entities db = new Hawthor_HS_Entities())
{
// Loads information into the DataGridView from the Administrators db.
var adminLIST = (from c in db.Administrators
select new
{
AID = c.AID,
FirstName = c.FName,
LastName = c.LName
}).ToList();
ADDdataGridView.DataSource = adminLIST;
// loads information into the AdminID combo box in the EDIT tab.
cboAdminID.DisplayMember = "AID";
cboAdminID.ValueMember = "AID";
cboAdminID.DataSource = adminLIST;
//loads information into the AID combo box in the DELETE tab.
cboAID.DisplayMember = "AID";
cboAID.ValueMember = "AID";
cboAID.DataSource = adminLIST;
}
}
答案 0 :(得分:0)
您可以在执行ID
后从模型类中获取SaveChanges()
。在您的情况下,您可以从ID
对象中获取addAdministrator
/ p>
try
{
using (Hawthor_HS_Entities db = new Hawthor_HS_Entities())
{
Administrator addAdministrator = new Administrator();// currently adding only the AID and nothing else.
{
addAdministrator.FName = txtAdminFname.Text;
addAdministrator.LName = txtAdminLname.Text;
addAdministrator.Password = txtNewPass.Text;
}
db.Administrators.Add(addAdministrator);
db.SaveChanges();
DataGridLoad();
int Id = addAdministrator.ID; // you can able to get the id for the record you attempt to save.
MessageBox.Show("Success! New Administrator was Added");
}
}
catch (Exception)
{
MessageBox.Show("Error: Could not Add new Administrator. Please try again.");
}
答案 1 :(得分:0)
根据您的评论,您在数据库中成功获取数据,但是在正确加载数据方面存在问题,所以
让我举一个例子,可能会对你有帮助。如果没有,请告诉我,
您可以使用以下代码加载datagridview
var context=new Hawthor_HS_Entities();
BindingSource bi = new BindingSource();
bi.DataSource = context.Administrators;
dataGridView1.DataSource = bi;
dataGridView1.Refresh();