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:
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;
} } }
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 = "";
}