Click here to Skip to main content
16,004,647 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am a beginner, trying to develop a C# windows form application.

I have prepared the code to store 3 inputs in a database:
3 fields are: lvl, posid, upperposid.

I need to now modify the code such that the user input will be accepted only if the "upperposid" already exists in the database. And "upperposid" values are not already stored in database. Only one "upperposid" value will be stored and all the details entered by user will be children of that "upperposid"

For example, if user gives input as:
lvl=2, posid="child" and upperposid="parent",
then data will only be accepted if the value "parent" exists atleast once in upperposid column.
So as another example, if user gives input:

lvl="3"
posid="CIV"
upperposid="RET"

Then data will only be accepted and stored if "RET" exists at least once in "upperposid column".

Please guide on this. Please provide the C# code itself, if you can. I have given code below. Thanks

What I have tried:

//Code:
        //This is Class called "WBSMASTERDB"
        namespace Actual_Project
       {
       public class WBSMASTERDB
       {
        public static SqlConnection GetConnection()
        {
            string connStr = @"Data Source=
      (LocalDB)\v11.0;AttachDbFilename=C:\Users\ABC\Documents\Visual Studio
      2013\Projects\Actual Project\Actual Project\ActualProj_DB.mdf;Integrated
      Security=True;";
           SqlConnection conn = new SqlConnection(connStr);
           return conn;
       }
       public static void AddData(string posid, string lvl, string upperposid)
     {

               string insStmt = "INSERT INTO WBS_MASTER (posid, upperposid,lvl)
               VALUES (@lvl, @upperposid, @posid)";
               SqlConnection conn = GetConnection();
               SqlCommand insCmd = new SqlCommand(insStmt, conn);
               insCmd.Parameters.AddWithValue("@posid", posid);
               insCmd.Parameters.AddWithValue("@upperposid", upperposid);
               insCmd.Parameters.AddWithValue("@lvl", lvl);
               try { conn.Open(); insCmd.ExecuteNonQuery(); }
               catch (SqlException ex) { throw ex; }
               finally { conn.Close(); }
       }
       public static List<wbsmastercls> GetData()
       {
           List<wbsmastercls> DataList = new List<wbsmastercls>();
           SqlConnection conn = GetConnection();
           string selStmt = "SELECT * FROM WBS_MASTER";
           SqlCommand selCmd = new SqlCommand(selStmt, conn);
           try
           {
               conn.Open();
               SqlDataReader reader = selCmd.ExecuteReader();
               while (reader.Read())
               {
                   WBSMASTERCLS apc = new WBSMASTERCLS();
                   apc.posid = (string)reader["posid"].ToString();
                   apc.upperposid = (string)reader["upperposid"].ToString();
                   apc.lvl = (string)reader["lvl"].ToString();
                   DataList.Add(apc);
               }
               reader.Close();
           }
           catch (SqlException ex) { throw ex; }
           finally { conn.Close(); }
           return DataList;
       } } }

      //Code
    //This is Class called "WBSMASTER [Here the AddData() is called]"

     namespace Actual_Project
      {
     public partial class WBSMASTER : Form
     {

       public WBSMASTER()
       {
           InitializeComponent();
       }
       private void button1_Click(object sender, EventArgs e)
       {

               WBSMASTERDB.AddData(textBox1.Text, textBox2.Text,textBox3.Text);
               textBox1.Text = "";
               textBox2.Text = "";
               textBox3.Text = "";
       }
Posted
Updated 1-Jun-17 7:41am
Comments
Richard Deeming 1-Jun-17 14:26pm    
catch (SqlException ex) { throw ex; }

Please don't do that. You've just destroyed the stack trace of the exception, which is going to make it almost impossible to track down the real cause of the error.

If you must rethrow an exception, use:
catch (SomeException ex) { throw; }


But in this case, since you're not doing anything with the exception, just remove the catch clause entirely.

Something like this:
string sql = "SELECT COUNT(*) FROM WBS_MASTER WHERE upperposid = @upperposid";

using (SqlConnection conn = new SqlConnection(connString))
{
	SqlCommand cmd = new SqlCommand(sql, conn);
	cmd.ParametersAddWithValue("@upperposid", upperposid);
	try
	{
		conn.Open();
		Int32 count = (Int32) cmd.ExecuteScalar();
		return (count > 0);
	}
	catch (Exception ex)
	{
		Debug.Print(ex.Message);
		return false;
	}
}
 
Share this answer
 
Comments
Member 13235643 2-Jun-17 1:16am    
It is not working. It is not giving an exception or storing any data in database, when user clicks submit button after entering the details.
RickZeeland 2-Jun-17 8:28am    
LocalDb can give problems, and when you try with a normal SQL Server database ?
The line string insStmt = "INSERT INTO WBS_MASTER (posid, upperposid,lvl)
VALUES (@lvl, @upperposid, @posid)";

is wrong I think, the values of posid and lvl are switched.
Generally, if your creating hierarchical data relationships in database, you have more than a single table to do it.

In your case, upperposid could better be represented as a separate list of values which you manage as to its content in whatever way you create upperposid values.

The other table would be the lvl and posid values along with a reference to the upperposid containing table.

Their should be a foreign-key relationship between the two tables so you cannot add any values that aren't in upperposid.

Note that this is all handled by SQL, not your code.

Your code should, however, use the upperposid table to offer a list of acceptable values for input - so the user cannot misspell or otherwise mess things up.
 
Share this answer
 
Comments
Member 13235643 2-Jun-17 1:27am    
But I need to implement the logic in the code itself. Some logic in the AddData() {I am assuming}which shows some kind of error message to user if the "upperposid" input does not match with any value in the database table.

I was thinking of using if..else STATEMENT or the IF EXISTS() statement, but I don't know where to use it and how to write it correctly.
W Balboos, GHB 2-Jun-17 6:28am    
Two thoughts come to mind here:
1) You're doing this for yourself: why not do it the right way?
2) It's homework - and the idea of that is for you to learn by doing.

By-the-way: IF EXISTS() is SQL, so if that's acceptable why wouldn't my solution be acceptable?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900