使用gridview中的复选框插入所选数据

时间:2012-01-27 19:36:29

标签: c# asp.net gridview checkbox sql-server-2008-r2

当我使用复选框在gridview中选择时,我希望它将数据插入数据库,但它不会添加它。我的代码如下,请看我出错的地方。

public partial class HomeTeamCheckList : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        LiveGameReporting Window
        SubmitLineUp.Attributes.Add("onclick", "PassValues();");

        SubmitLineUp.Text = "Submit " + Session["HomeTeam"] + "'s Line Up";
    }

    protected void SubmitLineUp_Click(object sender, EventArgs e)
    {
        String GameID = string.Empty;
        String Name = string.Empty;
        String Number = string.Empty;

        int GKGVCount = GoalKeeperGridView.Rows.Count;


        foreach (GridViewRow gkrow in GoalKeeperGridView.Rows)
        {
            GameID = (String)Session["GameID"];
            Number = gkrow.Cells[0].Text;
            Name = gkrow.Cells[1].Text;

             SqlConnection connection = new SqlConnection(("Data Source=ROBEL-HP;Initial Catalog=RocoSportsDB;Integrated Security=True"));

            {
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = connection;
                cmd.CommandText = @"INSERT INTO HTLineUp (GameID, HomeTeamLineUpNo, HomeTeamLineUpName) VALUES (@GameID,@Number,@Name)";

                cmd.Parameters.AddWithValue("@GameID", GameID);
                cmd.Parameters.AddWithValue("@Number", Number);
                cmd.Parameters.AddWithValue("@Name", Name);

                cmd.ExecuteNonQuery();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

两个想法:

  • 使用try-catch查看是否收到任何SQL错误。
  • 检查cmd.ExecuteNonQuery();的返回值,以查看是否有任何行实际受影响/插入。

像这样:

 SqlConnection connection = new SqlConnection(("Data Source=ROBEL-HP;Initial Catalog=RocoSportsDB;Integrated Security=True")); 
 try
 { 
    SqlCommand cmd = new SqlCommand(); 
    cmd.Connection = connection; 
    cmd.CommandText = @"INSERT INTO HTLineUp (GameID, HomeTeamLineUpNo, HomeTeamLineUpName) VALUES (@GameID,@Number,@Name)"; 

    cmd.Parameters.AddWithValue("@GameID", GameID); 
    cmd.Parameters.AddWithValue("@Number", Number); 
    cmd.Parameters.AddWithValue("@Name", Name); 

    // use a debugger to see if any rows were actually affected / inserted
    int rowsAffected = cmd.ExecuteNonQuery(); 
 } 
 catch(SQLException error)
 {
     // Use a debugger to see if you are getting an error on execution
     string errorText = error.message;
 }

您的查询字符串看起来没问题,因此可能是权限错误。但上述步骤将帮助您追踪它。