Compare Selected Date and Database Date - c#

My logic is:
"if selected date is a match with the database date from Holiday table, return message as "OK"
I have already formatted date in the code shown below. When I do test with hardcoded database date, the code works fine.
How to get database date from my Holiday table?
PS: Holiday table includes different dates so system needs to loop and search every row in Holiday table.
Code:
[System.Web.Services.WebMethod]
public static string GetDateFromDB(DateTime compareDate)
{
string selectedDate = compareDate.ToString("yyyy/MM/dd");
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LoginDBConnectionString1"].ConnectionString);
SqlCommand com = new SqlCommand("SELECT * from Holiday", conn);
SqlDataAdapter sqlDa = new SqlDataAdapter(com);
DataTable dt = new DataTable();
sqlDa.Fill(dt);
//hardcoded is ok
string dbDateString = "2019-02-20";
DateTime date1 = DateTime.ParseExact(dbDateString.Split(' ')[0], "yyyy/MM/dd", null);
string dateDB = date1.ToString("yyyy/MM/dd");
if (dateDB == selectedDate)
{
return "OK";
}
else
{
return "NG";
}
}

string selectedDate = compareDate.ToString("yyyy/MM/dd");
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LoginDBConnectionString1"].ConnectionString);
SqlCommand com = new SqlCommand("SELECT * from Holiday where Date='" + selectedDate + "'", conn);
SqlDataAdapter sqlDa = new SqlDataAdapter(com);
DataTable dt = new DataTable();
sqlDa.Fill(dt);
if (dt == null || dt.Rows.Count() == 0)
return "NG";
else
return "OK";

You said you have multi rows so you just can return "OK" or "NG" after loop all row (or break when have error):
[System.Web.Services.WebMethod]
public static string GetDateFromDB(DateTime compareDate)
{
string selectedDate = compareDate.ToString("yyyy/MM/dd");
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LoginDBConnectionString1"].ConnectionString);
SqlCommand com = new SqlCommand("SELECT * from Holiday", conn);
SqlDataAdapter sqlDa = new SqlDataAdapter(com);
DataTable dt = new DataTable();
sqlDa.Fill(dt);
if (dt != null && dt.Rows.Count > 0)
{
string formatDate = "yyyy/MM/dd";
foreach (DataRow dr in dt.Rows)
{
string dateString = dr["yourColumnName"].ToString();
if (string.IsNullOrEmpty(dateString))
{
continue; // Or set error or something
}
dateString = DateTime.ParseExact(dateString.Split(' ')[0], formatDate, null).ToString(formatDate);
if (dateString.Equals(compareDate))
{
// Do something
}
else
{
// Set error message or something
}
}
// Check after loop and return "OK" or "NG"
}
}

Related

Set value of combo box to collected value from source

I have a form with two combo boxes which both have a list from a database. In this case one is a list of countries and based on the value selected there, the second list is updated to show only the cities that belong to the selected country. After that, the values are combined and stored in my program like "city, country".
When I open my form I retrieve that information and separate the values back to just country and city. All working. The trouble I have now is that the comboboxes should display the retrieved values if the correspond to a value found in the list/database. I tried as shown below, but that is not working. I guess it has something to do with adding a new row to the database to show "--Select Country--" and "--Select City--".
I hope you can point me in the right direction. Thank you all in advance for your replies.
comboBoxCountry.SelectedValue = comboBoxCountry.FindString(country);
comboBoxCity.SelectedValue = comboBoxCity.FindString(city);
public partial class FormPropertyEditor : Form
{
//Connect to local database.mdf
SqlConnection con = new SqlConnection("Data Source = (LocalDB)\\MSSQLLocalDB;AttachDbFilename=" +
#"C:\Users\gleonvanlier\AppData\Roaming\Autodesk\ApplicationPlugins\MHS Property Editor\Database.mdf;" +
"Integrated Security=True;Connect Timeout=30;User Instance=False;");
DataRow dr;
public FormPropertyEditor()
{
InitializeComponent();
ReadProperties();
refreshdata();
}
public void refreshdata()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from TblCountries Order by CountryName", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
dr = dt.NewRow();
dr.ItemArray = new object[] { 0, "--Select Country--" };
dt.Rows.InsertAt(dr, 0);
comboBoxCountry.ValueMember = "CountryID";
comboBoxCountry.DisplayMember = "CountryName";
comboBoxCountry.DataSource = dt;
comboBoxCountry.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBoxCountry.AutoCompleteSource = AutoCompleteSource.ListItems;
}
private void comboBoxCountry_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBoxCountry.SelectedValue.ToString() != null)
{
int CountryID = Convert.ToInt32(comboBoxCountry.SelectedValue.ToString());
refreshstate(CountryID);
}
}
public void refreshstate(int CountryID)
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from TblCities where CountryID= #CountryID Order by CityName", con);
cmd.Parameters.AddWithValue("CountryID", CountryID);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
dr = dt.NewRow();
dr.ItemArray = new object[] { 0, 0, "--Select City--" };
dt.Rows.InsertAt(dr, 0);
comboBoxCity.ValueMember = "CityID";
comboBoxCity.DisplayMember = "CityName";
comboBoxCity.DataSource = dt;
comboBoxCity.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBoxCity.AutoCompleteSource = AutoCompleteSource.ListItems;
}
private void ReadProperties()
{
string progId = "Inventor.Application";
Type inventorApplicationType = Type.GetTypeFromProgID(progId);
Inventor.Application invApp = (Inventor.Application)Marshal.GetActiveObject(progId);
//Get the active document in Inventor
Document oDoc = (Document)invApp.ActiveDocument;
ReadProperties readProperties = new ReadProperties();
//Read Customer
string txtCustomer = readProperties.ReadCustomProperty("Customer", oDoc).ToString();
this.textBoxCustomer.Text = txtCustomer;
//Read Location
string txtLocation = readProperties.ReadCustomProperty("Location", oDoc).ToString();
try
{
string[] location = txtLocation.Split(',', ' ');
string city = location[0];
string country = location[1];
comboBoxCountry.SelectedValue = comboBoxCountry.FindString(country);
comboBoxCity.SelectedValue = comboBoxCity.FindString(city);
}
catch (Exception e)
{
string city = string.Empty;
string country = string.Empty;
}
}
This solved it:
comboBoxCountry.SelectedIndex = comboBoxCountry.FindStringExact(country);
comboBoxCity.SelectedIndex = comboBoxCity.FindStringExact(city);

Setting value to ComboBoxs item #C

I'm trying to set values on items in combobox, but everytime I try so I get the result 'null'. Am I defining the value wrong or am I trying to get the value in a wrong way?
// Setting the value
sqlCmd.CommandText = "SELECT Id, Ime FROM Unajmljivaci WHERE Aktivan = 0";
conn.Open();
using (var reader = sqlCmd.ExecuteReader())
{
while (reader.Read())
{
cmbUnajmljivaci.Items.Add(new { Id = reader["Id"].ToString(), Ime = reader["Ime"].ToString() });
}
cmbUnajmljivaci.ValueMember = "Id"; // <---
cmbUnajmljivaci.DisplayMember = "Ime";
}
//Retrieving the value
sqlCmd.Parameters.AddWithValue("#SifraUnajmljivca", Convert.ToString(cmbUnajmljivaci.SelectedValue));
using (SqlConnection sqlConn = new SqlConnection("CONNECTION STRING"))
{
DataSet ds = new DataSet();
SqlCommand sqlCmd = sqlConn.CreateCommand();
sqlConn.Open();
SqlDataAdapter SQA_DataAdapter = new SqlDataAdapter(sqlCmd);
SQA_DataAdapter.SelectCommand = new SqlCommand("SELECT Id, Ime FROM Unajmljivaci WHERE Aktivan = 0", sqlConn);
SQA_DataAdapter.Fill(ds, "Table");
if (ds != null)
if (ds .Tables.Count > 0)
{
cmbUnajmljivaci.ValueMember = "Id";
cmbUnajmljivaci.DisplayMember = "Ime";
cmbUnajmljivaci.DataSource = ds.Tables[0];
}
sqlConn.Close();
}
You need to set the data source of the combobox.
Try getting the Value like this:
dynamic dyn = cmbUnajmljivaci.SelectedItem;
string s = dyn.Id;
Or even inline like this:
//Retrieving the value
sqlCmd.Parameters.AddWithValue("#SifraUnajmljivca", Convert.ToString(((dynamic)cmbUnajmljivaci.SelectedItem).Id);
Sample Code for Reference to your problem,
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add();
dt.Columns.Add("ID");
dt.Columns.Add("Name");
dt.Rows.Add("0", "Item1");
dt.Rows.Add("1", "Item2");
For inserting the item with specified index you need to use the below code
//Insert the item into the collection with specified index
foreach (DataRow row in dt.Rows)
{
int id = Convert.ToInt32(row["ID"]);
string name=row["Name"].ToString();
comboBox1.Items.Insert(id,name);
}
Always index should start from 0 (Zero).
Easy way to add values to combobox
comboBox1.DataSource=dt;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";

ArgumentNullException while dealing with DataTable and DataAdapter in c#

i am using DataAdapter to fill my DataTable with query as Stored Procedure.
But there is an exception ArgumentNullExceptioncoming when i try to Fill DataTable. I tested the query and its working fine.
Here's my code:
if (!IsPostBack)
{
Session["NewsId"] = Convert.ToInt32(Request.QueryString["news"]);
if (Session["NewsId"] != null && Convert.ToInt32(Session["NewsId"]) != 0)
{
id = Convert.ToInt32(Session["NewsId"]);
}
}
da = new SqlDataAdapter("NewsGallerySelect", con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("#NewsID", SqlDbType.Int).Value = id;
da.Fill(dt);
if (dt.Rows.Count > 0)
{
rptrNews.DataSource = dt;
rptrNews.DataBind();
foreach (DataRow row in dt.Rows)
{
lblShrtDesc.Text = row["ShortDesc"].ToString();
lblShrtDesc2.Text = row["ShortDesc"].ToString();
lblDesc.Text = row["NewsDesc"].ToString();
lblDesc2.Text = row["NewsDesc"].ToString();
lblDate.Text = row["NewsDate"].ToString();
}
}

How to clear datatable values when using two datatables?

I have two DataTables after passing query the second DataTable Shows the FirstDataTable values. Please find my code
My connection class is
public class Connection
{
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
public SqlDataAdapter ad;
public DataTable dt = new DataTable();
public DataTable gettable(string cmdtxt)
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
conn.Open();
dt.Clear();
ad = new SqlDataAdapter(cmdtxt, conn);
ad.Fill(dt);
return dt;
}
}
My code is
String qry="";
DataTable shiftdt = new DataTable();
DataTable empdt = new DataTable();
qry = "select ShiftID from ShiftGroup where ShiftName="#Shift";
shiftdt = conn.gettable(qry);
qry = "select EmpCode from EmployeeShift where GroupCode="#gcode";
empdt = conn.gettable(qry);
First,shiftdt shows proper output ShiftID and when go ahead empdt shows first column as ShiftID and Second Column as EmpCode. Actually I dont want ShiftID in empdt. And again when I go ahead Shiftdt values changes to EmpCode. May I know the reason?
I tried `Dot net learner,when I change code as per him, I have a
dropdown class it shows error like
`Error 8 'Sample.Connection' does not contain a definition for 'dt' and no extension method 'dt' accepting a first argument of type 'Sample.Connection' could be found (are you missing a using directive or an assembly reference?
. That calss is
public class Dropdown
{
Connection con = new Connection();
public void dropdwnlist(string qry, DropDownList ddl)
{
con.gettable(qry);
if (con.dt.Rows.Count > 0)
{
if (con.dt.Columns.Count == 2)
{
string str1 = con.dt.Columns[0].ColumnName.ToString();
string str2 = con.dt.Columns[1].ColumnName.ToString();
ddl.DataValueField = str1;
ddl.DataTextField = str2;
ddl.DataSource = con.dt;
ddl.DataBind();
con.dt.Columns.Remove(str1);
con.dt.Columns.Remove(str2);
}
else
{
string str = con.dt.Columns[0].ColumnName.ToString();
ddl.DataValueField = str;
ddl.DataTextField = str;
ddl.DataSource = con.dt;
ddl.DataBind();
con.dt.Columns.Remove(str);
}
}
ddl.Items.Insert(0, ("--Select--"));
}
}
You Have dt as Global variable in Class So Please Make it Local variable for Function or Assign new DataTable on starting of gettable function.
Your revised Code should be
public class Connection
{
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
public SqlDataAdapter ad;
public DataTable gettable(string cmdtxt)
{
DataTable dt = new DataTable();
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
conn.Open();
dt.Clear();
ad = new SqlDataAdapter(cmdtxt, conn);
ad.Fill(dt);
return dt;
}
}
I had revised code as per your need please check it.
You shouldn't use Connection Class DataTable(dt) Variable to bind dropdown instead Declare DataTable Variable Local for Dropdown Class and use it to bind Dropdown.
Revised Code for Dropdown Class
public class Dropdown
{
Connection con = new Connection();
public void dropdwnlist(string qry, DropDownList ddl)
{
DataTable dt =con.gettable(qry);
if (dt.Rows.Count > 0)
{
if (dt.Columns.Count == 2)
{
string str1 = dt.Columns[0].ColumnName.ToString();
string str2 = dt.Columns[1].ColumnName.ToString();
ddl.DataValueField = str1;
ddl.DataTextField = str2;
ddl.DataSource = dt;
ddl.DataBind();
dt.Columns.Remove(str1);
dt.Columns.Remove(str2);
}
else
{
string str = dt.Columns[0].ColumnName.ToString();
ddl.DataValueField = str;
ddl.DataTextField = str;
ddl.DataSource = dt;
ddl.DataBind();
dt.Columns.Remove(str);
}
}
ddl.Items.Insert(0, ("--Select--"));
}
}

no row at position 0

I have the following code snippet:
if (!IsPostBack)
{
if (Request.QueryString["id"] != null)
{
string catid = Request.QueryString["id"].ToString();
Query1 = "select senderfirstname from messages where senderid='" + catid + "'";
adap = new SqlDataAdapter(Query1, con);
DataTable dt = ds.Tables["messages"];
DataRow dr = dt.Rows[0];
if (dt.Rows.Count > 0)
{
Session["table"] = dr["senderfirstname"].ToString();
}
else
{
Label1.Text = "error";
}
}
}
But I'm getting an error as:
There is no row at position 0.
I have the same query in sql server, but my table has contents for this query.
You are not loading data in to the DataSet. You have to call SqlDataAdapter.Fill to load the data in the DataSet. Also assign the row in the condition where you check that Rows count is greater then zero for not getting exception when not row exists.
if (!IsPostBack)
{
if (Request.QueryString["id"] != null)
{
string catid = Request.QueryString["id"].ToString();
Query1 = "select senderfirstname from messages where senderid='" + catid + "'";
adap = new SqlDataAdapter(Query1, con);
adap.Fill(ds);
DataTable dt = ds.Tables["messages"];
if (dt.Rows.Count > 0)
{
DataRow dr = dt.Rows[0];
Session["table"] = dr["senderfirstname"].ToString();
}
else
{
Label1.Text = "error";
}
}
}
Please check your updated code below
if (!IsPostBack)
{
if (Request.QueryString["id"] != null)
{
string catid = Request.QueryString["id"].ToString();
Query1 = "select senderfirstname from messages where senderid='" + catid + "'";
adap = new SqlDataAdapter(Query1, con);
DataTable dt = ds.Tables["messages"];
if (dt.Rows.Count > 0)
{
DataRow dr = dt.Rows[0];
Session["table"] = dr["senderfirstname"].ToString();
}
else
{
Label1.Text = "error";
}
}

Categories

Resources