I want to block the duplicate dates before inserting it into database.If a week with the same date is already exist in the database,when selecting the same date it should pop-up with the error message "this dates are already chosen".
Example:
If Week 1 is 1.1.2015 to 5.1.2015 stored in database and when Week 2 is also selecting the same date from 1.1.2015 to 5.1.2015,it should give the error message.
How to accomplish this,suggest some ideas.
This is my database.
I am using SQL database.Where the selected dates are stored in "datedif" column in database. With the "daywk" column I'm selecting the dates by week wise and displayed in grid.
I want to block the duplicate date when inserting into "datedif" column.
my code so far.
using (SqlConnection con2 = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=Z:\NewTimeTable\NewTimeTable\App_Data\Admindetail.mdf;Integrated Security=True"))
{
var fromdate = DateTime.Parse(txtfromdate.Text);
var todate = DateTime.Parse(txttodate.Text);
var datedif1 = (todate - fromdate).Days;
var sqlInsert = new SqlCommand("INSERT INTO datelist ([datedif],[batch],[daywk],[semester],[weekbatch],[subject],[facultyname],[facultyid],[WeekMonth]) VALUES (#datedif,#batch,#daywk,#semester,#weekbatch,#subject,#facultyname,#facultyid,#weekMonth)", con2);
var sqlParamater = sqlInsert.Parameters.Add("#datedif", SqlDbType.Date);
var sqlParameter1 = sqlInsert.Parameters.Add("#batch", SqlDbType.NVarChar);
var sqlParameter2 = sqlInsert.Parameters.Add("#daywk", SqlDbType.NVarChar);
var sqlParameter3 = sqlInsert.Parameters.Add("#semester", SqlDbType.NVarChar);
var sqlParameter4 = sqlInsert.Parameters.Add("#weekbatch", SqlDbType.NVarChar);
var sqlParameter5 = sqlInsert.Parameters.Add("#subject", SqlDbType.NVarChar);
var sqlParameter6 = sqlInsert.Parameters.Add("#facultyname", SqlDbType.NVarChar);
var sqlParameter7 = sqlInsert.Parameters.Add("#facultyid", SqlDbType.NVarChar);
var sqlParameter8 = sqlInsert.Parameters.Add("#WeekMonth", SqlDbType.NVarChar);
con2.Open();
for (var i = 0; i <= datedif1; i++)
{
var consecutiveDate = fromdate.AddDays(i);
sqlParamater.Value = consecutiveDate;
sqlParameter1.Value = batch1;
sqlParameter2.Value = dayweek;
sqlParameter3.Value = semester;
sqlParameter4.Value = weekbatch;
sqlParameter5.Value = subject;
sqlParameter6.Value = faculty;
sqlParameter7.Value = facultyid;
sqlParameter8.Value = weekmonth;
sqlInsert.ExecuteNonQuery();
}
con2.Close();
}
}
List persons = new List();
using (SqlConnection connection = new SqlConnection("Data Source=(local);Initial Catalog=AdventureWorks2014;Integrated Security=SSPI"))
using (SqlCommand cmd = new SqlCommand("SELECT BusinessEntityID AS ID, FirstName, MiddleName, LastName FROM Person.Person", connection))
{
connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
// Check is the reader has any rows at all before starting to read.
if (reader.HasRows)
{
throw new ApplicationExcetion("Data is duplicated");
}
}
}
before insert into database. just query first.
if query have exist data(duplicated data). then throw exception
Related
I am trying to sort a datatable into a DataSet. I want to sort by the Status Column in "DESC". But I am not aware how to go about this. I have tried the suggested solutions online but I seem not to be doing something right. Here is what I have tried, albeit, I have commented out the sorting lines of the code as they do not work for me. How can I sort my table using the Status column in Desc?
[WebMethod(EnableSession = true)]
public List < TaskListClass > getTasks() {
var userId = Session["UserId"].ToString();
List < TaskListClass > objB = new List < TaskListClass > ();
try {
using(var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnString"].ToString())) {
connection.Open();
DataSet Myds = new DataSet();
// Myds.Tables[0].DefaultView.Sort = "Status desc";
SqlDataAdapter sqldr = new SqlDataAdapter();
string ProcName = "getTasks";
SqlCommand cmd = new SqlCommand(ProcName, connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#userId", SqlDbType.VarChar, 900).Value = userId;
sqldr.SelectCommand = cmd;
sqldr.Fill(Myds);
DataTable dt = Myds.Tables[0];
// DataTable dt = Myds.Tables[0].DefaultView.ToTable();
for (int i = 0; i < dt.Rows.Count; i++) {
objB.Add(new TaskListClass() {
Id = Convert.ToString(dt.Rows[i]["Id"]),
Subject = Convert.ToString(dt.Rows[i]["Subject"]),
Customer = Convert.ToString(dt.Rows[i]["Customer"]),
Sender = Convert.ToString(dt.Rows[i]["Sender"]),
Receiver = Convert.ToString(dt.Rows[i]["Receiver"]),
Priority = Convert.ToString(dt.Rows[i]["Priority"]),
StartDate = Convert.ToString(dt.Rows[i]["StartDate"]),
EndDate = Convert.ToString(dt.Rows[i]["EndDate"]),
Status = Convert.ToString(dt.Rows[i]["Status"]),
OnProgress = Convert.ToString(dt.Rows[i]["OnProgress"]),
});
}
}
} catch (Exception e) {
msg = e.ToString();
}
return objB;
}
Ok, a few things.
first up, a dataset is a collection of tables - "many tables" possible.
But you have ONE table, so why use a dataset? I see no need. Just use a single data table for this.
And this will reduce the code.
So, I suggest this, or close to this:
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnString"].ToString()))
{
using (var cmd = new SqlCommand("getTasks", connection))
{
connection.Open();
cmd.CommandType = CommandType.StoredProcedure;
DataTable dt = new DataTable();
cmd.Parameters.Add("#userId", SqlDbType.VarChar).Value = userId;
dt.Load(cmd.ExecuteReader());
// now sort the datatable
dt.DefaultView.Sort = "Status DESC";
// now fill out our object with each row
foreach (DataRow OneRow in dt.Rows)
{
objB.Add(new TaskListClass()
{
Id = OneRow["Id"].ToString(),
Subject = OneRow["Subject"].ToString(),
Customer = OneRow["Customer"].ToString(),
Sender = OneRow["Sender"].ToString(),
Receiver = OneRow["Receiver"].ToString(),
Priority = OneRow["Priority"].ToString(),
StartDate = OneRow["StartDate"].ToString(),
EndDate = OneRow["EndDate"].ToString(),
Status = OneRow["Status"].ToString(),
OnProgress = OneRow["OnProgress"].ToString(),
}); ;
}
}
}
}
return objB;
The way the current code is written, you could add this after the for-loop:
objB = objB.OrderByDescending(t => t.Status).ToList();
Depending of the datatype of Status, it might be sorted alphabetically.
var dataRow = dt.AsEnumerable().OrderByDescending(x => x.Field<string>("Status")).ToList();
foreach (var item in dataRow)
{
//Enter your Code Here
}
Here dt is your datatable.
dataRow is a set of list.
After get the data list, you can asign it to your "objB".
I am trying to update a databse entry under a specific id in my table when the users enter their ID number in a textBox.
At the moment it updates but updates all entries in my table except the entry containing the users ID number.
This is the code I am currently using:
private void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=DEVELOPMENT\ACCESSCONTROL;Initial Catalog=ACCESSCONTROL;User ID=sa;Password=P#55w0rd123");
SqlCommand check_User_Name = new SqlCommand("SELECT Id FROM NewVisitor WHERE (IDNumber = #IDNumber)", con);
check_User_Name.Parameters.AddWithValue("#IDNumber", idNumber_TxtBox.Text);
con.Open();
int UserExist = (int)check_User_Name.ExecuteScalar();
if (UserExist > 0)
{
var connetionString = #"Data Source=DEVELOPMENT\ACCESSCONTROL;Initial Catalog=ACCESSCONTROL;User ID=sa;Password=P#55w0rd123";
var sql = "UPDATE NewVisitor SET PersonVisit = #PersonVisit, PurposeVisit = #PurposeVisit, Duration = #Duration, Disclaimer = #Disclaimer";
try
{
using (var connection = new SqlConnection(connetionString))
{
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#PersonVisit", SqlDbType.NVarChar).Value = personVisiting_TxtBox.Text;
command.Parameters.Add("#PurposeVisit", SqlDbType.NVarChar).Value = purposeOfVisit_CMBox.SelectedItem;
command.Parameters.Add("#Duration", SqlDbType.Date).Value = duration_dateTimePicker1.Value.Date;
command.Parameters.Add("#Disclaimer", SqlDbType.NVarChar).Value = disclaimer_CHKBox.Checked;
connection.Open();
command.ExecuteNonQuery();
}
}
}
The whole table has many more fields but would like to just update the above fields within that specific ID.
Thanks
You forgot the WHERE clause on the UPDATE statement, telling it specifically which records to update. It sounds like you just want to add the exact same WHERE clause that you have on your SELECT:
var sql = "UPDATE NewVisitor SET PersonVisit = #PersonVisit, PurposeVisit = #PurposeVisit, Duration = #Duration, Disclaimer = #Disclaimer WHERE (IDNumber = #IDNumber)";
And don't forget to add the paramter for it:
command.Parameters.Add("#IDNumber", SqlDbType.Int).Value = idNumber_TxtBox.Text;
You may need to convert the input value to an integer first, I'm not 100% certain (it's been a while since I've had to use ADO.NET directly). Something like this:
if (!int.TryParse(idNumber_TxtBox.Text, out var idNumber))
{
// input wasn't an integer, handle the error
}
command.Parameters.Add("#IDNumber", SqlDbType.Int).Value = idNumber;
Can anyone point me to where I make a mistake, I want to put a new sql query where I will read the data from the database and put them in my function, and in the end they will be displayed at the exit in the colon ("stunden") which currently appears on the first query SUM (zei.ZPZ_Std100) AS ZPZ_Std100
This looks like my entire code in the button
using (SqlConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["TestControl.Properties.Settings.DB"].ConnectionString))
{
boAPI4.Login login = new boAPI4.Login();
string cS = login.GetConnectionString();
DataAccess dA = new DataAccess(cS);
int userID = dA.getLpeID(login.GetBoUserNr());
PRAESENZZEIT q = new PRAESENZZEIT();
q.ZPZ_LPE_ID = userID;
if (db.State == ConnectionState.Closed)
db.Open();
string query = "SELECT per.LPE_Nr, zei.ZPZ_LPE_ID, zei.ZPZ_Datum, SUM (zei.ZPZ_Std100) AS ZPZ_Std100" +
" FROM DB.dbo.Z_PRAESENZZEIT zei INNER JOIN DB.dbo.A_PERSONAL per ON zei.ZPZ_LPE_ID = per.LPE_ID" +
$" WHERE zei.ZPZ_Datum BETWEEN '{dtFromDate.Value}' AND '{dtToDate.Value}' AND zei.ZPZ_LPE_ID='{userID.ToString()}' GROUP BY per.LPE_Nr, zei.ZPZ_LPE_ID, zei.ZPZ_Datum ORDER BY zei.ZPZ_Datum, per.LPE_Nr;";
pRAESENZZEITBindingSource.DataSource = db.Query<PRAESENZZEIT>(query, commandType: CommandType.Text);
List<PRAESENZZEIT> listid = new List<PRAESENZZEIT>();
PRAESENZZEIT pra = new PRAESENZZEIT();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TestControl.Properties.Settings.DB"].ConnectionString);
string sql = "SELECT ZPZ_Von,ZPZ_bis FROM DB.dbo.Z_PRAESENZZEIT WHERE ZPZ_LPE_ID='196'";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
pra.ZPZ_Von = Convert.ToDateTime(dr["ZPZ_Von"]);
pra.ZPZ_Bis = Convert.ToDateTime(dr["ZPZ_bis"]);
listid.Add(pra);
}
dataGridView1.DataSource = listid;
con.Close();
DateTime kommen = DateTime.Now;
kommen = pra.ZPZ_Von;
if (pra.ZPZ_Von.TimeOfDay < new TimeSpan(8, 5, 0))
pra.ZPZ_Von = new DateTime(pra.ZPZ_Von.Year, pra.ZPZ_Von.Month, pra.ZPZ_Von.Day, 8, 0, 0);
DateTime gehen = DateTime.Now;
gehen = pra.ZPZ_Bis;
TimeSpan arbeitszeit = pra.ZPZ_Bis - pra.ZPZ_Von;
}
Currently, at the exit I get 0.
So, I need data that pass through the datetime variable
This is how it goes through the variables but returns the result as if it did not address base data, what's the problem? I understand if time [ZPZ_VON 07:45] that the exit should be 08:00..
SQL QUERY SELECT ZPZ_Von,ZPZ_bis FROM DB.dbo.Z_PRAESENZZEIT WHERE ZPZ_LPE_ID='196'
CODE:
List<PRAESENZZEIT> listid = new List<PRAESENZZEIT>();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TestControl.Properties.Settings.DB"].ConnectionString);
string sql = "SELECT ZPZ_Von, ZPZ_bis FROM DB.dbo.Z_PRAESENZZEIT WHERE ZPZ_LPE_ID='196'";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
while (dr.Read())
{
PRAESENZZEIT pra = new PRAESENZZEIT();
pra.ZPZ_Von = Convert.ToDateTime(dr["ZPZ_Von"]);
pra.ZPZ_Bis = Convert.ToDateTime(dr["ZPZ_bis"]);
listid.Add(pra);
DateTime kommen = DateTime.Now;
kommen = pra.ZPZ_Von;
if (pra.ZPZ_Von.TimeOfDay < new TimeSpan(8, 5, 0))
pra.ZPZ_Von = new DateTime(pra.ZPZ_Von.Year, pra.ZPZ_Von.Month, pra.ZPZ_Von.Day, 8, 0, 0);
DateTime gehen = DateTime.Now;
gehen = pra.ZPZ_Bis;
TimeSpan arbeitszeit = pra.ZPZ_Bis - pra.ZPZ_Von;
}
con.Close();
DATABASE QUERY RESULT:
You were initializing the pra class outside the while loop. Which doesn't add new record in the list listid every time read DataRow from DataReader.
Try this below code:
using (SqlConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["TestControl.Properties.Settings.DB"].ConnectionString))
{
boAPI4.Login login = new boAPI4.Login();
string cS = login.GetConnectionString();
DataAccess dA = new DataAccess(cS);
int userID = dA.getLpeID(login.GetBoUserNr());
PRAESENZZEIT q = new PRAESENZZEIT();
q.ZPZ_LPE_ID = userID;
if (db.State == ConnectionState.Closed)
db.Open();
string query = "SELECT per.LPE_Nr, zei.ZPZ_LPE_ID, zei.ZPZ_Datum, SUM (zei.ZPZ_Std100) AS ZPZ_Std100" +
" FROM DB.dbo.Z_PRAESENZZEIT zei INNER JOIN DB.dbo.A_PERSONAL per ON zei.ZPZ_LPE_ID = per.LPE_ID" +
$" WHERE zei.ZPZ_Datum BETWEEN '{dtFromDate.Value}' AND '{dtToDate.Value}' AND zei.ZPZ_LPE_ID='{userID.ToString()}' GROUP BY per.LPE_Nr, zei.ZPZ_LPE_ID, zei.ZPZ_Datum ORDER BY zei.ZPZ_Datum, per.LPE_Nr;";
pRAESENZZEITBindingSource.DataSource = db.Query<PRAESENZZEIT>(query, commandType: CommandType.Text);
List<PRAESENZZEIT> listid = new List<PRAESENZZEIT>();
//PRAESENZZEIT pra = new PRAESENZZEIT(); //Needs to be inside the while loop.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TestControl.Properties.Settings.DB"].ConnectionString);
string sql = "SELECT ZPZ_Von,ZPZ_bis FROM DB.dbo.Z_PRAESENZZEIT WHERE ZPZ_LPE_ID='196'";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
var listid = ConvertDataTable<PRAESENZZEIT>(dt);
dataGridView1.DataSource = listid;
con.Close();
}
private static List<T> ConvertDataTable<T>(DataTable dt)
{
List<T> data = newList<T>();
foreach (DataRowrow in dt.Rows)
{
Titem = GetItem<T>(row);
data.Add(item);
}
return data;
}
private static TGetItem<T>(DataRow dr)
{
Type temp = typeof(T);
T obj =Activator.CreateInstance<T>();
foreach (DataColumncolumn in dr.Table.Columns)
{
foreach (PropertyInfopro in temp.GetProperties())
{
if (pro.Name == column.ColumnName)
pro.SetValue(obj,dr[column.ColumnName], null);
else
continue;
}
}
return obj;
}
Whenever the code is executed, it always return that the ID value is not supplied that will cause an error. Would someone please show me where is my error? In some queries there is also sqlcommand.Parameters.Clear(); which is not included in this code.
The #ID should be pointing to the first column in the datagridview, where I can also set the match with the ID (primary key) in the table via SQL Management.
using (SqlCommand InsUpd = new SqlCommand(
#"IF EXISTS(SELECT 1 FROM dbo.Bokfuppg WHERE dbo.Bokfuppg.ID = #ID)
UPDATE dbo.bokfuppg
SET fnr = #Fnr, kto = #Kto, Ukto = #Ukto, avd = #Avd, prod = #Prod, proj = #Proj, ant = #Ant, bel = #Bel, Text = #Text, vbel = #Vbel, period = #Period
WHERE dbo.Bokfuppg.ID = #ID
ELSE
INSERT INTO dbo.bokfuppg(Fnr, Kto, Ukto, Avd, Prod, Proj, ant, bel, text, vbel, period) VALUES(#Fnr, #Kto, #Ukto, #Avd, #Prod, #Proj, #Ant, #Bel, #Text, #Vbel, #Period)", con))
{
con.Open();
using (SqlTransaction tr = con.BeginTransaction())
{
InsUpd.Transaction = tr;
InsUpd.Parameters.Add("#ID", SqlDbType.Int);
InsUpd.Parameters.Add("#Fnr", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Kto", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Ukto", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Avd", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Prod", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Proj", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Ant", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Bel", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Text", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Vbel", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Period", SqlDbType.NVarChar);
foreach (DataGridViewRow item in dataGridViewBokfuppg.Rows)
{
InsUpd.Parameters["#ID"].Value = item.Cells[0].Value;
InsUpd.Parameters["#Fnr"].Value = textBox1.Text;
InsUpd.Parameters["#Kto"].Value = item.Cells[1].Value;
InsUpd.Parameters["#Ukto"].Value = item.Cells[2].Value;
InsUpd.Parameters["#Avd"].Value = item.Cells[3].Value;
InsUpd.Parameters["#Prod"].Value = item.Cells[4].Value;
InsUpd.Parameters["#Proj"].Value = item.Cells[5].Value;
InsUpd.Parameters["#Ant"].Value = item.Cells[6].Value;
InsUpd.Parameters["#Bel"].Value = item.Cells[7].Value;
InsUpd.Parameters["#Text"].Value = item.Cells[8].Value;
InsUpd.Parameters["#Vbel"].Value = item.Cells[9].Value;
InsUpd.Parameters["#Period"].Value = item.Cells[10].Value;
InsUpd.ExecuteNonQuery();
}
tr.Commit();
}
}
MessageBox.Show("Record Updated Successfully");`
I am trying to run multiple queries within a loop. The first query runs ok as I can see it when I step through the code.
However the second query (which is within a loop) is supposed to run depending on the value held from the first. When the loop runs based on that value it seems to be ignoring the query. I put a label to display in place of the query and it displayed so I believe how I have opened/closed my connection is not correct.
c# code:
protected void Page_Load(object sender, EventArgs e)
{
// Get the session of the user
string staffid = Session["StaffId"].ToString();
//Proxy on page load to check IsActive Status
string DefaultConnection = WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection myConnection = new SqlConnection(DefaultConnection);
myConnection.Open();
//select the userdetail specific to the logged in user using parameterisation
string query = "SELECT ProxyStatus.ProxyStatusId, ProxyStatus.FunctionId, ProxyStatus.StartDate, ProxyStatus.EndDate, ProxyStatus.IsActive FROM ProxyStatus INNER JOIN Staff ON Staff.StaffId = ProxyStatus.Proxee WHERE (Staff.StaffId = #StaffId)";
DateTime thisDay = DateTime.Today;
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("#staffid", staffid);
SqlDataReader rdr = myCommand.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
Session["StartDate"] = rdr["StartDate"].ToString();
Session["EndDate"] = rdr["EndDate"].ToString();
Session["ProxyStatusId"] = rdr["ProxyStatusId"].ToString();
Session["FunctionId"] = rdr["FunctionId"].ToString();
// Get the session of StartDate and endate, use the session value in a query to compare against the current date
string startdate = Session["StartDate"].ToString();
string enddate = Session["EndDate"].ToString();
string proxystatus = Session["ProxyStatusId"].ToString();
DateTime startdatedata = Convert.ToDateTime(startdate);
DateTime enddatedata = Convert.ToDateTime(enddate);
if (startdatedata > thisDay)
{
string DefaultConnection2 = WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection myConnection2 = new SqlConnection(DefaultConnection2);
myConnection2.Open();
string query2 = "UPDATE ProxyStatus SET ProxyStatus.IsActive = 'False' WHERE ProxyStatus.ProxyStatusId = #proxystatus";
myCommand.Parameters.AddWithValue("#newproxystatus", proxystatusnew);
SqlCommand myCommand2 = new SqlCommand(query2, myConnection2);
myCommand2.ExecuteNonQuery();
}
}
}
else
{
rdr.Close();
}
}
}
}
Shouldn't the lines be
SqlCommand myCommand2 = new SqlCommand(query2, myConnection2);
myCommand.ExecuteNonQuery();
be
SqlCommand myCommand2 = new SqlCommand(query2, myConnection2);
myCommand2.ExecuteNonQuery();
instead? The first "myCommand" will still be in use with "rdr".