using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace datagridview { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string flagpack = "3"; SqlConnection conn = new SqlConnection(@"server = 192.168.1.159;database =testdb;UID=sa;PWD=062455xzy"); string sqlPack = "select top 1* from dbo.Table_1 Where flag=@GrdFlag order by id desc"; SqlCommand cmd = new SqlCommand(sqlPack, conn); SqlParameter parameterGridFlag = new SqlParameter("@GrdFlag", SqlDbType.NVarChar); parameterGridFlag.Value = flagpack; cmd.Parameters.Add(parameterGridFlag); try { conn.Open(); SqlDataAdapter da = new SqlDataAdapter(sqlPack, conn); DataSet ds = new DataSet(); da.Fill(ds); conn.Close(); ////查询的数据显示到datagridview string grdPackTime = ds.Tables[0].Rows[0]["functime"].ToString(); string grdBatch = ds.Tables[0].Rows[0]["batch"].ToString(); string grdSoftWare = ds.Tables[0].Rows[0]["software"].ToString(); string grdClientName = ds.Tables[0].Rows[0]["clientname"].ToString(); string grdSerialNo = ds.Tables[0].Rows[0]["serialno"].ToString(); string grdImei = ds.Tables[0].Rows[0]["imei"].ToString(); string grdModuleSn = ds.Tables[0].Rows[0]["modulesn"].ToString(); string grdflag = ds.Tables[0].Rows[0]["flag"].ToString(); string grdBox = ds.Tables[0].Rows[0]["box"].ToString(); string[] row = { grdPackTime, grdBatch, grdSoftWare, grdClientName, grdSerialNo, grdImei, grdModuleSn, grdflag, grdBox }; ////给dataGridViewScan控件添加数据 dataGridViewPack.Rows.Add(row); ////datagridview显示排序-降序 this.dataGridViewPack.Sort(this.dataGridViewPack.Columns[0], ListSortDirection.Descending); } catch(SqlException ex) { MessageBox.Show(ex.Message + ex.StackTrace, "Exception Details"); conn.Close(); } finally { conn.Close(); } } } } 简单的功能,就是把MSsql查到的数据输入到datagridview显示,但是一直提示“必须声明标量变量@GrdFlag”,可已经声明了,谢谢 |
|
70分 |
SqlDataAdapter da = new SqlDataAdapter(sqlPack, conn); 这一句改为 ==> SqlDataAdapter da = new SqlDataAdapter(cmd); |
30分 |
SqlDataAdapter da = new SqlDataAdapter(sqlPack, conn);
=》这个是直接查询了。但是你用了变量。 而变量是在SqlParameter 里面定义并赋值。所以你直接使用 SqlDataAdapter da = new SqlDataAdapter(sqlPack, conn); 所以会报标量变量未声明 |
自己去查看下SqlDataAdapter的构造方法。 |