如何使用一个组合框用Sql数据库数据填充文本框

本文关键字:Sql 数据库 数据 文本 填充 组合 何使用 一个 | 更新日期: 2023-09-27 17:59:47

大家好,大家都是SQL数据库函数的新手,但已经用c#编码了大约一年了,现在还不太擅长,但我已经做到了!

我目前正在创建一个足球应用程序,为了编辑球员和比赛,我想使用一个下拉组合框从SQL数据库中检索数据,然后填充其他文本框和组合框。我自己也尝试过,但不知道哪里出了问题。

在表单加载时,我的连接打开,我填充数据集,并执行此方法来填充我的combobox

private void Navigate()
{
   string showPlayers = "SELECT * From Add_Players";
   SqlCommand cmdData = new SqlCommand(showPlayers, conn);
   SqlDataReader myReader = cmdData.ExecuteReader();
   while (myReader.Read())
   {
      comboEditPlayer.Items.Add(myReader[0]);
   }
   conn.Close();
}

之后在组合框中选择索引更改方法我有这个代码

private void comboEditPlayer_SelectedIndexChanged(object sender, EventArgs e)
{
   try
   {
      conn.Open();
      string showPlayers = "SELECT * From Add_Players WHERE Player_ID ='" 
      + comboEditPlayer + "'   ;";
      SqlCommand cmdData = new SqlCommand(showPlayers, conn);
      SqlDataReader myReader = cmdData.ExecuteReader();
      while (myReader.Read())
      {
         comboEditPlayerPos.Items.Add(myReader[1]);
         txtEditPlayerName.Text = myReader[2].ToString();
         txtEditPlayerSecond.Text = myReader[3].ToString();
         comboEditPlayerStatus.Items.Add(myReader[4]);
      }
      conn.Close();
      conn.Dispose();
   } 
   catch (Exception comboFail)
   {
      MessageBox.Show(comboFail.ToString());
   }
}

我被告知这个代码是开放的,我需要使用参数化查询来防止黑客的尝试,我已经开始了,但不知道我应该在代码中添加什么参数,因为它低于

private void comboEditPlayer_SelectedIndexChanged(object sender, EventArgs e)
{
   string connectionString =
      ZimbFootball.Properties.Settings.Default.Football2ConnectionString;
   using (SqlConnection connection = new SqlConnection (connectionString))
   {
      connection.Open();
      using (SqlCommand command = new SqlCommand(
               "SELECT * From Add_Players WHERE Player_ID =" 
               + comboEditPlayer.SelectedValue + "", connection))
      {
         command.Parameters.Add(new SqlParameter ("",));
      }
   }
}

感谢所有帮助,请对我宽容:p

如何使用一个组合框用Sql数据库数据填充文本框

您可以使用ComboBox的值向集合添加一个参数,然后执行查询并从读取器中读取值

private void comboEditPlayer_SelectedIndexChanged(object sender, EventArgs e)
{
      string connectionString =
          ZimbFootball.Properties.Settings.Default.Football2ConnectionString;
      using (SqlConnection connection = new SqlConnection (connectionString))
      using (SqlCommand command = new SqlCommand(
                    "SELECT * From Add_Players WHERE Player_ID =@id", connection))
      {
          connection.Open();
          command.Parameters.AddWithValue("@id", comboEditPlayer.Text);
          using(SqlDataReader myReader = command.ExecuteReader())
          {
              while (myReader.Read())
              {
                    comboEditPlayerPos.Items.Add(myReader[1]);
                    txtEditPlayerName.Text = myReader[2].ToString();
                    txtEditPlayerSecond.Text = myReader[3].ToString();
                    comboEditPlayerStatus.Items.Add(myReader[4]);
              }
          }
       }
 }