SQL数据读取到文本框

本文关键字:文本 读取 数据 SQL | 更新日期: 2023-09-27 18:19:37

我正在尝试将数据从数据库中获取到文本中!我粘贴的代码运行良好,没有给我任何异常,但问题是它无法从它获取System.Data.SqlClient.SqlDataReader的数据库中获取所需的数据。

请帮我解决这个问题。。。

////代码/////

private void ReplaceBookmarkText(Microsoft.Office.Interop.Word.Document doc, string bookmarkName,string text)
{
   object objI=1 ;
   object count = 7;
   object oCount = Microsoft.Office.Interop.Word.WdConstants.wdForward;
   object oUnit = Microsoft.Office.Interop.Word.WdUnits.wdCharacter;
   int number;
   //here is your name, store it where ever you want:
   bookmarkName = doc.Bookmarks.get_Item(ref objI).Name;
   //bookmarkEnd = doc.Bookmarks.get_Item(ref objI).End;
   //bookmarkStart = doc.Bookmarks.get_Item(ref objI).Start;
   number = doc.Bookmarks.get_Item(ref objI).Range.MoveEnd(ref oUnit, ref count);
   //bookmarkEnd = doc.Bookmarks.get_Item(ref objI).Start;
   string bookmarkValue = doc.Bookmarks.get_Item(ref objI).Range.Text;
   MessageBox.Show(bookmarkValue);
   string db_name = "";
   try
   {
      sql_con = new SqlConnection(con_str);
      sql_con.Open();
      //"SELECT FirstName FROM ContactPerson WHERE (Contact_ID = " + fNameTemp + ")");
      // select s_name from student where s_reg = '11-ARID-4204'
      // string sql_query = ("select s_name from student where (s_reg = " + txtboxrollno + ")");
      //"Select * from logintable where password=" + "'TextBox1.Text'";
      sql_cmd = sql_con.CreateCommand();
      string qrery = ("select s_name from student where (s_reg = " + "'txtboxrollno.text'" + ")");
      SqlCommand cmd = new SqlCommand(qrery,sql_con);
      //sql_cmd.CommandText = ("select s_name from student where (s_reg = " + txtboxrollno.Text.Trim() + ")");
      cmd.ExecuteNonQuery();
      MessageBox.Show(cmd.ToString());
      SqlDataReader sdr; 
      sdr = cmd.ExecuteReader();
      //textBox1.Text = sdr.ToString();
      db_name = textBox1.Text;
      while(sdr.Read())
      {
         //textBox1.Text = sdr["s_name"].ToString();
         textBox1.Text = cmd.ExecuteScalar().ToString();
         //txtpatientid.Text = command.ExecuteScalar().ToString();
         //fNameTextBox.Text = sdr["FirstName"].ToString();
      }
   }
}

SQL数据读取到文本框

这样的东西怎么样:

sql_cmd = sql_con.CreateCommand();
string qrery = "select s_name from student where (s_reg = @s_reg)";
SqlCommand cmd = new SqlCommand(qrery,sql_con);
cmd.Parameters.AddWithValue("@s_reg", txtboxrollno.Text);
textBox1.Text = cmd.ExecuteScalar() as string;

我还要推荐一些其他的东西。但让我们从这个开始。这将获得第一行的第一个结果,并将其放入文本框中。