【发布时间】:2016-09-06 06:46:47
【问题描述】:
我是编程世界和 Stack Overflow 的新手,所以请原谅“菜鸟”的问题。
我在这里有这个方法(链接到 Windows 窗体),想法是将信息添加到文本框并将其添加到 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;
}
}
【问题讨论】:
-
您可以在
SaveChanges()执行后从模型类中获取一次ID。在您的情况下,您可以从addAdministrator对象中获取ID,例如addAdministrator.ID -
Fname、Lname 和密码字段是否写入数据库?
-
你使用了 db.Administrators.Add(addAdministrator);对于添加,你试过这个db.AddToAdministrators(addAdministrator);,你在db之后看到这个选项了吗?
-
'Fname、Lname 和密码字段是否写入数据库? - 是的。 'db.AddToAdministrators(addAdministrator);' db之后没有出现。 “InsertOnSubmit”也不显示(我在stackflow上看到了这个选项,但无法正常工作)
-
我猜您的问题一定出在您的 DataGrid 列定义或绑定中。向我们展示 DataGridLoad 方法和 DataGrid 定义
标签: c# database datagridview