如何使用DataGridView查看数据库记录?

时间:2016-04-12 05:10:41

标签: c# .net datagridview ado.net

这是我的第一个ADO.NET项目,我需要完成我的教授案例研究。我想创建一个Windows窗体并放置一个Textbox来输入caseid并使用一个按钮find。当我单击查找按钮时,我可以看到caseid并根据SQL Select语句分配了解决方案。我找到一个示例并使用SqlDataReader,但是当我点击查找时,我无法在表单上看到结果。

那么,你能给我一些建议如何设计数据网格视图吗?

由于 索菲亚

我实现了这样的代码:

private void Find_Click(object sender, EventArgs e)
{
        string querystring = "SELECT * FROM AssignedSolution WHERE CASEID = @caseid";
        SqlCommand Vcom = new SqlCommand(querystring, vcon1);
        Vcom.Parameters.AddWithValue("@caseid", txtCASEID.Text);
        SqlDataReader rdr = null;

        try
        {
            Vcom.Connection = vcon1;
            Vcom.ExecuteNonQuery();
            rdr = Vcom.ExecuteReader();

            while (rdr.Read())
            {
                Console.WriteLine(rdr[0]);
            }

            Vcom.Dispose();
        }
        catch (Exception ex)
        {
            MessageBox.Show("error.occured" + ex.Message);
        }
        finally
        {
            vcon1.Close();
            vcon1.Dispose();
        }
}

4 个答案:

答案 0 :(得分:0)

DataGridViewRowCollection.Add Method

        while (rdr.Read())
        {
            Console.WriteLine(rdr[0]);
            dataGridView1.Rows.Add(rdr[0], rdr[1], rdr[2], rdr[3], ..);
        }

答案 1 :(得分:0)

你可以尝试这样的事情(当然如果你的项目是 WinForm ):

 private void Find_Click(object sender, EventArgs e)
 {
     DataTable table = null;
     using (SqlConnection vcon1 = new SqlConnection(this.connectionString))
     {
         try
         {
             vcon1.Open();
             SqlCommand Vcom = vcon1.CreateCommand();
             Vcom.CommandText = "SELECT * FROM AssignedSolution WHERE CASEID = @caseid";
             Vcom.Parameters.Add(new SqlParameter("@caseid", txtCASEID.Text));

             using (SqlDataAdapter adapter = new SqlDataAdapter(Vcom))
             {
                 table = new DataTable();
                 adapter.Fill(table);
             }
         }
         catch (Exception ex)
         {
             //Handle your exception;   
         }
     }

     dataGridView1.DataSource = table;
 }

答案 2 :(得分:0)

如何从头开始。 添加HTML页面:

 <form id="form1" runat="server">
<div>
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>

</div>
</form>

在Default.aspx.cs中

 protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        FillGridView();
    }
}
    public void FillGridView()
{
    try
    {
string connectionString = WebConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
        string selectSQL = "SELECT * FROM YourTableName";
        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand(selectSQL, con);
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();

        adapter.Fill(ds, "YourTableName");

        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
    catch
    {
        Response.Write("<script> alert('Connection error') </script>");
    }
}

您还需要在web.config文件中存储连接字符串

<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="ConnectionStringName" connectionString="Data Source=localhost\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI"/>
</connectionStrings>

答案 3 :(得分:0)

索菲亚,

您可以使用SqlDataAdapter或SqlDataReader与DataTable一起在Datagridview中显示数据

//使用SqlDataAdapter

    private void Find_Click(object sender, EventArgs e)
    {
        string ConStr = Convert.ToString(ConfigurationManager.AppSettings["strConn"]);
        SqlConnection vcon1 = new SqlConnection(ConStr);
        vcon1.Open();
        string querystring = "SELECT * FROM AssignedSolution WHERE CaseId = @caseid";
        SqlCommand Vcom = new SqlCommand(querystring, vcon1);
        Vcom.Parameters.AddWithValue("@caseid",Convert.ToInt32(txtCASEID.Text));


        try
        {
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(Vcom);
            da.Fill(dt);
            dataGridView1.DataSource = dt;                

        }

        catch (Exception ex)
        {
            MessageBox.Show("error.occured" + ex.Message);

        }

        finally
        {
            Vcom.Dispose();
            vcon1.Close();
            vcon1.Dispose();
        }
    }

    // Use SqlDataReader
    private void button1_Click(object sender, EventArgs e)
    {
        string ConStr = Convert.ToString(ConfigurationManager.AppSettings["strConn"]);
        SqlConnection vcon1 = new SqlConnection(ConStr);
        vcon1.Open();
        string querystring = "SELECT * FROM AssignedSolution WHERE CaseId = @caseid";
        SqlCommand Vcom = new SqlCommand(querystring, vcon1);
        Vcom.Parameters.AddWithValue("@caseid", Convert.ToInt32(txtCASEID.Text));
        SqlDataReader dr = null;

        try
        {
            DataTable dt = new DataTable();
            dr = Vcom.ExecuteReader();              
            dt.Load(dr);  
            dataGridView1.DataSource = dt;

        }

        catch (Exception ex)
        {
            MessageBox.Show("error.occured" + ex.Message);

        }

        finally
        {
            dr.Close();
            Vcom.Dispose();
            vcon1.Close();
            vcon1.Dispose();
        }
    }