我正在做一个作业,我必须在Web表单中填写信息,然后将该信息插入本地数据库,但是Webform上的一个字段与数据库中的另一个表相关联,并且我不确定如何实现可以执行此操作的联接。
我的数据库:
玩家 -(PK)玩家ID - 选手姓名 -JerseyNumber
统计 -(PK)StatId -玩家编号 -玩过的比赛 -比赛获胜 -助攻 -目标 -点数
我的WebForm请求:
玩家名称-下拉菜单, 进行过的比赛-文本框, 比赛获胜-文本框, 辅助-文字框, 目标-文字框, 添加按钮
这里是按钮单击事件中的内容
tblStatistic = (DataTable)Cache["tbl"];
DataRow newRow = tblStatistic.NewRow();
newRow["StatID"] = 0;
newRow["MatchesPlayed"] = txtMatchesPlayed.Text;
newRow["MatchesWon"] = txtMatchesWon.Text;
newRow["Assists"] = txtAssists.Text;
newRow["Goals"] = txtGoals.Text;
tblStatistic.Rows.Add(newRow);
adapter.InsertCommand = cmdBuilder.GetInsertCommand();
int rowsAffected = adapter.Update(tblStatistic);
if (rowsAffected == 1)
{
lblMessage.Text = "Stats inserted";
lblMessage.ForeColor = System.Drawing.Color.Green;
}
else
{
lblMessage.Text = "Stat not inserted";
lblMessage.ForeColor = System.Drawing.Color.Red;
}
我得到的错误是“ PlayerId不允许为空”。
答案 0 :(得分:0)
if you want to add row in Statistic you have to pass id of player as a FK
just add this line to your code i hope it works
newRow["PlayerID"] = int.parse(drpPlayer.selectedvalue);
it will be :
tblStatistic = (DataTable)Cache["tbl"];
DataRow newRow = tblStatistic.NewRow();
newRow["StatID"] = 0;
newRow["PlayerID"] = int.parse(drpPlayer.selectedvalue);
newRow["MatchesPlayed"] = txtMatchesPlayed.Text;
newRow["MatchesWon"] = txtMatchesWon.Text;
newRow["Assists"] = txtAssists.Text;
newRow["Goals"] = txtGoals.Text;
tblStatistic.Rows.Add(newRow);
adapter.InsertCommand = cmdBuilder.GetInsertCommand();
int rowsAffected = adapter.Update(tblStatistic);
if (rowsAffected == 1)
{
lblMessage.Text = "Stats inserted";
lblMessage.ForeColor = System.Drawing.Color.Green;
}
else
{
lblMessage.Text = "Stat not inserted";
lblMessage.ForeColor = System.Drawing.Color.Red;
}