Search code examples
c#sqldatagridviewtextboxwindows-forms-designer

Read sql string from textbox and display in datagridview


I am trying to create a database reader. where i add the query i want to run in the db in a textbox and then click the button and get the result in a datagridview

public partial class Form1 : Form
{
    SqlCommand cmd = new SqlCommand();
    SqlDataReader rdr;
    DataSet ds;
    SqlDataAdapter da;

    public Form1()
    {
        InitializeComponent();
    }

    private void btnEnter_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("Data Source=Apples;Initial Catalog=Abpee;Integrated Security=True;user id=sash;password=12345");
        con.Open();
        cmd.CommandText = txtSqlString.Text.Trim();
        cmd.Connection = con;
        rdr = cmd.ExecuteReader();
        bool temp = false;
        while (rdr.Read())
        {
            txtSqlString.Text = Convert.ToString(rdr[0].ToString());
            temp = true;
        }
        if (temp == false)
            MessageBox.Show("not found");
        con.Close();

        con.Open();
        ds = new DataSet();
        da = new SqlDataAdapter(" ", con);
        da.Fill(ds);
        con.Close();
        dgvResult.ReadOnly = true;
        dgvResult.DataSource = ds.Tables;
    }
}

Solution

  • You don't set any sql command for SqlDataAdapter, and don't set DataSource properly.

        da = new SqlDataAdapter(txtSqlString.Text.Trim(), con);
        da.Fill(ds);
        con.Close();
        dgvResult.ReadOnly = true;
        dgvResult.DataSource = ds.Tables[0];
    

    Plus at least wrap it with try .. catch to inform user when it fails. And this is rather dangerous code I should say.