Question ExecuteNonQuery: CommandText property has not been initialized RSS

redrose4u293

New member
Joined
Aug 24, 2021
Messages
4
Programming Experience
Beginner
C#:
try
{
    con = new SqlConnection(cs);
    con.Open();
    string p_comp="";

    if (cmbH_ID.Text == "Select" || cmbH_ID.Text == "")
    {
        p_comp = "INSERT INTO Supply (SUPPLY_DATE,B_ID,D_I_ID,M_ID,ST_ID) VALUES (@SUPPLY_DATE,@B_ID,@D_I_ID,@M_ID, @ST_ID) ";
        cmd = new SqlCommand(p_comp);
        cmd.Connection = con;
        cmd.Parameters.AddWithValue("@SUPPLY_DATE", dateTimePicker1.Value.Date);
        cmd.Parameters.AddWithValue("@M_ID", textBox2.Text);
        cmd.Parameters.AddWithValue("@B_ID", textBox3.Text);
        cmd.Parameters.AddWithValue("@D_I_ID", cmbDis_ID.Text);
        cmd.Parameters.AddWithValue("@ST_ID", cmbS_id.Text);
    }

    if (cmbS_id.Text == "Select" || cmbS_id.Text == "")
    {
        p_comp = "INSERT INTO Supply (SUPPLY_DATE,B_ID,D_I_ID,H_ID,M_ID) VALUES (@SUPPLY_DATE,@B_ID,@D_I_ID,@H_ID,@M_ID) ";
        cmd = new SqlCommand(p_comp);
        cmd.Connection = con;
        cmd.Parameters.AddWithValue("@SUPPLY_DATE", dateTimePicker1.Value.Date);
        cmd.Parameters.AddWithValue("@H_ID", cmbH_ID.Text);
        cmd.Parameters.AddWithValue("@M_ID", textBox2.Text);
        cmd.Parameters.AddWithValue("@B_ID", textBox3.Text);
        cmd.Parameters.AddWithValue("@D_I_ID", cmbDis_ID.Text);
    }

    cmd = new SqlCommand(p_comp);
    cmd.Connection = con;
    cmd.Parameters.AddWithValue("@SUPPLY_DATE", dateTimePicker1.Value.Date);
    cmd.Parameters.AddWithValue("@H_ID", cmbH_ID.Text);
    cmd.Parameters.AddWithValue("@M_ID", textBox2.Text);
    cmd.Parameters.AddWithValue("@B_ID", textBox3.Text);
    cmd.Parameters.AddWithValue("@D_I_ID", cmbDis_ID.Text);
    cmd.Parameters.AddWithValue("@ST_ID", cmbS_id.Text);

    cmd.ExecuteReader();
    MessageBox.Show("Successfully saved", "Supply Details", MessageBoxButtons.OK, MessageBoxIcon.Information);
    btnSave.Enabled = false;

    if (con.State == ConnectionState.Open)
    {
        con.Close();
    }

    con.Close();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
 
Last edited by a moderator:
There's a lot wrong here, but let's address the issues in stages.

Firstly, I have reformatted your code to make it more readable. The indenting was all over the place and the there were wads of completely illogical and unnecessary blank lines. Different developers use blank lines slightly differently but there should always be a consistent method to it. Work out what you're doing and stick to it. You should almost never have two blank lines together and never more than two. Doing so just makes the code harder to read, especially in a context like this. There's no excuse for not using consistent indenting.

Furthermore, your post is of an unacceptable quality. An error message and some code are never adequate. Sometimes we'll be able to work out what's going on and sometimes we won't, but you won't know ahead of time so ALWAYS provide a proper post. That means writing a FULL and CLEAR explanation of the problem first, including a description of what you're trying to achieve, how you're trying to achieve it and what happens when you try. You should always include both any relevant error messages and the relevant code, formatted appropriate, as text, so at least you've done that. You can also add images if they add value. The last thing you should do is write a title that summarises the problem. Your post is an error message and code, so not adequate.
 
You really need to stop what you're doing and learn how to debug, because even the simplest debugging here would almost certainly have revealed the issue. There are far more issues besides but the immediate issue appears to be the fact that you set p_comp to an empty string and, if you don't enter either of your if blocks, that value never changes. That means that if you get past the two if blocks without entering either then, when you get to this line:
C#:
cmd = new SqlCommand(p_comp);
you are creating a command with an empty string as the CommandText. That should make it glaringly obvious why you get that error message and you'd have seen it for yourself if you had debugged your code.

ALWAYS debug your code BEFORE posting a question here or anywhere else. VS has various debugging tools and there are tutorials on the web on how to use them. You'll solve many of your issues for yourself and not only save yourself time by doing so but learn more along the way.

There's a lot more wrong with that code and I may address it later but I don't have time now and at least we've covered the specific issue. You should still learn how to debug and then prove to yourself that what I've described is what's happening. If it's actually something else that's the problem, debugging will likely show that up too.
 
I've also moved this thread to a more appropriate forum. Please post in the most specific forum that applies to the topic. C# General should only be for topics that aren't covered by another forum.
 
It's your assignment so you need to do it yourself. It would be cheating for me to do your homework for you. I've told you what the problem is so now you have to work out how to fix it.

That said, here's the sort of thing you ought to be doing. Just create one SqlCommand object with all the columns and all the parameters. When it comes to those columns that you may or may not be setting, use a conditional expression to set the Value of the parameter to either an appropriate value or NULL, e.g.
C#:
myCommand.Parameters.Add("@ColumnName", SqlDbType.VarChar, 50).Value = someBooleanExpression ? someValue : (object)DBNull.Value;
If you omit a column from an INSERT statement then, unless the database specifies a default value, it will be set to NULL implicitly. You setting it explicitly has the same effect, so it's easier to do that so that you only need one INSERT statement for all possibilities.
 
I can do my best but i can't remove the error so kindly give me the code because i have only three days left for submit my assignment
 
I'm not going to do your homework for you. If you can't write the code yourself then you don't deserve to get the marks for the assignment. I don't say that with malice but assignments would be pointless if everyone just got strangers on the internet to do their work for them. I'm quite prepared to help further but I will not be writing your code for you.

The best advice I can give you is what I always say to beginners. That is that you should not try to go from an idea to code in one hop because you're pretty much guaranteed to write nonsense code if you don't know what the code has to. You should work out what the code has to do first, i.e. not just the end result but the steps to get there. That's doesn't require any programming experience at all because the steps would be the same for a totally manual process. You just have to think logically, which I realise is not always as easy as it sounds. Break the process down into smaller and smaller steps and then write those steps down. That list of steps is your algorithm. You can test that algorithm manually, without any code or even a computer. Once you have a working algorithm, THEN you should start writing code. The code you write should be an explicit implementation of the algorithm. Because each step is as elementary as possible, the code to implement it will be a few lines at the most, so it's very simple to implement each individual step. You can always compare your code to your algorithm and, if you encounter an issue, you can always point to the exact step in your algorithm you're having trouble with. If you do that then you'll never need to come with us with a big block of code that is supposed to produce some result X but doesn't and you have no idea why. This process may seem laborious and it's not as sexy as just writing code so people try to take shortcuts. The mess you're in is the result of that. Do it right and you'll encounter fewer issues and be able to solve those issues more easily. If you don't get the marks for an assignment or two in order to learn that then so be it. Not what you want, obviously, but you don't have an implicit right to get those marks.
 
I can do my best but i can't remove the error so kindly give me the code because i have only three days left for submit my assignment
Sure. I'm feeling generous. Insert the following before line 31 of your original code:
C#:
if (string.IsNullOrWhiteSpace(p_comp))
{
    MessageBox.Show("I'm too lazy to figure out why p_comp is an empty string, so I asked random people on the internet to do my homework for me.",
         "No query performed.", MessageBoxButtons.OK);
    return;
}
 
I will remember very well your message that if you ask someone for help, you will hear them instead of helping them ... especially Mr Skydiver i think you both gave me a best life lesson
 
But I did help you. You asked that no error be thrown when your function is called. With the code above, no error will be thrown because it detects that the command string is empty and so it does not perform a query thereby avoiding the error being thrown.

Now if you had asked for the query to still be performed, that is a different request.
 
Back
Top Bottom