0

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;
    }
}
2
  • 2
    and... what is the problem? Commented Jul 16, 2019 at 7:24
  • @TheGeneral the sql connection is fine, I think it does run the query I add in the textbox but doesnt run it correctly and then doesnt display the results in the datagridview Commented Jul 16, 2019 at 7:29

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.