Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The SelectCommand property has not been initialized before calling 'Fill'. in WinForm

Tags:

c#

I am building a windows application using C#. In my login form, I'm getting Select Command property has not been initialized before calling fill method.

Here is the code:

public partial class frmlogin : Form
{
    SqlConnection con = new SqlConnection("Data Source=TH07L019;Initial Catalog=loginerror;Integrated Security=True");
    DataTable dt = new DataTable();
    SqlCommand cmd = new SqlCommand();
    SqlDataAdapter adp = new SqlDataAdapter();

    public frmlogin()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        cmd.Connection = con;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        con.Open();
        cmd.CommandText = "select * from login where username='" + txt1.Text + "' and password='" + txt2.Text +"'";
        adp.Fill(dt);
        if (dt.Rows.Count > 0)
        {
            frmmain main = new frmmain();
            main.Show();
        }
        else
        {
            MessageBox.Show("Please enter correct name and passowrd", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}
like image 610
Kaushik27 Avatar asked Apr 04 '13 06:04

Kaushik27


2 Answers

Another way to accomplish would be to simply pass the SQLCommand as an argument into your data adapter as follows -

SqlCommand cmd = new SqlCommand();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
like image 62
Helix Avatar answered Oct 30 '22 08:10

Helix


You have to specify select command of SqlDataAdapter before filling your table. You are not doing it. Your SqlCommand object is not connected in any way to your SqlDataAdapter.

 adp.SelectCommand=cmd;
like image 19
Arie Avatar answered Oct 30 '22 07:10

Arie