DataTable 应用以及 dataGridView的用法参考代码

        private void Form2_Load(object sender, EventArgs e)

        {

            textBox1.Text = "server=.;database=master;user=sa;pwd=123";

        }

        //点击查询

        private void button1_Click(object sender, EventArgs e)

        {



            SqlConnection coon = new SqlConnection(textBox1.Text);

            SqlCommand cmd = coon.CreateCommand();

            cmd.CommandText = "select*from " + textBox2.Text;

            coon.Open();

            SqlDataReader dr = cmd.ExecuteReader();

            //DataTable dt = null;

            //if (dr.HasRows)

            //{

            //    dt = new DataTable();

            //    dt.Columns.Clear();

            //    for (int i = 0; i < dr.FieldCount; i++)

            //    {

            //        dt.Columns.Add(dr.GetName(i));

            //    }

            //}

            //dt.Rows.Clear();

            //while (dr.Read())

            //{

            //    DataRow dtrow = dt.NewRow();

            //    for (int i = 0; i < dr.FieldCount; i++)

            //    {

            //        dtrow[i] = dr[i];

            //    }

            //    dt.Rows.Add(dtrow);

            //}

            //coon.Close();

            //dataGridView1.DataSource = dt;



        }

        public DataTable goujiantable()

        {

            DataTable dt = new DataTable();

            dt.Columns.Add("code");

            dt.Columns.Add("name");

            dt.Columns.Add("sex");



            DataRow dr = dt.NewRow();

            dr["code"] = "1001";

            dr["name"] = "张三";

            dr["sex"] = "";

            dt.Rows.Add(dr);



            return dt;



        }

        //临时表查询

        private void button1_Click_1(object sender, EventArgs e)

        {

            DataTable dt = goujiantable();

            dataGridView1.DataSource = dt;

        }



    }

}

 

你可能感兴趣的:(datagridview)