Select statement in SQL Server - c#

I'm trying to display student individual attendance records between two dates. When teachers select two dates, the records will be displayed in GridView control. However, I have a problem which other students' attendance records are being displayed too. I can't show only a student attendance records.
This is my C# code, once teacher clicked on view buttuon:
protected void ButtonView_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-H7KQUT1;Initial Catalog=SAOS;Integrated Security=True";
con.Open();
string query1 = "SELECT * FROM attendance WHERE Date between '" + datepicker.Text + "'AND'" + datepicker1.Text + "'";
SqlCommand sqlcomm = new SqlCommand(query1, con);
SqlDataAdapter sda = new SqlDataAdapter(sqlcomm);
DataTable dt = new DataTable();
sda.Fill(dt);
SqlDataReader sdr = sqlcomm.ExecuteReader();
if (sdr.Read())
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
else
{
Label7.Text = "No records found!!";
}
con.Close();
}
The problem is here:
string query1 = "SELECT * FROM attendance WHERE Date between '" + datepicker.Text + "'AND'" + datepicker1.Text + "'";
I have a column called Student_ID as the foreign key in table attendance.

string query1 = "SELECT * FROM attendance WHERE Date between #startDate AND #endDate and Student_ID = #studentId";
SqlCommand sqlcomm = new SqlCommand(query1, con);
sqlcomm.Parameters.Add("#startDate", SqlDbType.Date).Value = datepicker.Text;
sqlcomm.Parameters.Add("#endDate", SqlDbType.Date).Value = datepicker1.Text;
sqlcomm.Parameters.Add("#studentId", SqlDbType.Int).Value = 100;

Related

Having trouble populating textboxes from a combo box selection

I am trying to have the item selected from the combo box (Site PSI) auto-populate all the textboxes to the right. I have scoured the web and there is some data source selections and auotocomplete sections but they are not working. I have tried several steps that were resolved with a similar issue on this website but it is not working. Here is my code. the combobox is called cmbSitePSI and the text boxes txtSiteName, txtSiteLName, etc...I was able to autopopulate them from a grid but I am not using a grid. Please help, thank you so much in advance.
con.Open();
SqlDataAdapter da = new SqlDataAdapter(#"Select * from Site order by SitePSI", con);
DataTable dt = new DataTable();
da.Fill(dt);
SqlCommand cmd = new SqlCommand("Select SiteName, SiteLongName, SiteAddress1, SiteAddress2, SiteAddress3, SiteCity, SiteState, SiteZipCode, SiteCountry, " +
"SiteOperationsRegion from Site where SitePSI = '" + cmbSitePSI.Text + "'", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#SitePSI", int.Parse(cmbSitePSI.Text));
SqlDataReader dr = cmd.ExecuteReader();
dt1.Load(dr);
UPDATE
I have tried using this method but I have not been successful. I get squiggilies on these lines string sSiteName = r.GetString("SiteName");
private void CmbSitePSI_SelectedIndexChanged(object sender, EventArgs e)
{
con.Open();
SqlDataAdapter da2 = new SqlDataAdapter(#"Select * from Site where SitePSI = '" + cmbSitePSI + "'", con);
string constring = "Data Source=*********;Initial Catalog=DIETS;Integrated Security=True";
string Query = "Select * from Site where SitePSI = '" + cmbSitePSI.Text + "' ;";
SqlConnection condata = new SqlConnection(constring);
SqlCommand cmddata = new SqlCommand(Query, condata);
SqlDataReader r;
try
{
condata.Open();
r = cmddata.ExecuteReader();
while (r.Read())
{
string sSiteName = r.GetString("SiteName");
string sSiteLongName = r.GetString("SiteLongName");
txtSiteName.Text = sSiteName;
txtSiteLName.Text = sSiteLongName;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

Retrieve data from a another table and insert into a another

I'm trying to retrieve data from a table according to the ID number and insert it to another table. The program is in C# and database in MySQL.
The retrieving table name is student_dt and the table name i want to insert is student_att
Here's what I'm doing so far
private void button1_Click(object sender, EventArgs e)
{
cmd = new MySqlCommand();
cmd.CommandText = "Insert into student_att values(`id`, `nic`, `name`, `address`, `number`, `batch`)";
string Query1 = "select * from student_dt where id like '" + textBox1.Text + "%'";
if (textBox1.Text == "")
{
MessageBox.Show("Please provide all data");
}
else
{
con.Open();
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Inserted");
string Query = "select * from student_att ;";
MySqlCommand MyCommand2 = new MySqlCommand(Query, con);
MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
MyAdapter.SelectCommand = MyCommand2;
DataTable dTable = new DataTable();
MyAdapter.Fill(dTable);
dataGridView2.DataSource = dTable;
}
You can do from one query
string query = "insert into student_att (`id`, `nic`, `name`, `address`,
`number`, `batch`) select * from student_dt where id like '" + textBox1.Text + "%'"

Out of Range Error while accessing date from SQL Server

I want to fetch the maximum value of date from the table. But I always get an 'OutofRangeException' error. I changed my query several times.
Due_Date column has date data type
Due_Date_Sample is a string var
Due_Date_var is a DateTime var
My code:
using (SqlConnection sqlCon = new SqlConnection(Main.connectionString))
{
string commandString = "SELECT TOP 1 FORMAT(Due_Date,'dd-MM-yyyy') FROM Transactions WHERE Plot_Code='" + Plot_Code_var + "' ORDER BY Due_Date DESC;";
SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);
sqlCon.Open();
SqlDataReader dr = sqlCmd.ExecuteReader();
while (dr.Read())
{
date_control_var = 2;
Due_Date_Sample = (dr["Due_Date"].ToString());
Due_Date_var = DateTime.Parse(Due_Date_Sample.ToString());
}
dr.Close();
}
You need to give an alias to the selected value, e.g.: FORMAT(Due_Date,'dd-MM-yyyy') as Due_Date
You can do this:
using (SqlConnection sqlCon = new SqlConnection(Main.connectionString))
{
string commandString = "SELECT TOP 1 FORMAT(Due_Date,'dd-MM-yyyy') as Due_Date FROM Transactions where Plot_Code='" + Plot_Code_var + "' ORDER BY Due_Date DESC;";
SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);
sqlCon.Open();
SqlDataReader dr = sqlCmd.ExecuteReader();
while (dr.Read())
{
date_control_var = 2;
Due_Date_Sample = (dr["Due_Date"].ToString());
Due_Date_var = DateTime.Parse(Due_Date_Sample.ToString());
}
dr.Close();
}

How to use SQL count function

I want to show number of count in a Text Box
protected void PresentCalculator()
{
string cur_month = "May";
SqlDataAdapter da = new SqlDataAdapter("SELECT COUNT(EMP_CODE) FROM
Attendance where Month ='" + cur_month + "' and EMP_CODE='" + 2222 + "' ",
con);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
txtPresentDay.Text = Convert.ToString(count);
}
}
Instead of SqlDataAdapter use a SqlCommand
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand(v=vs.110).aspx
and get the value by calling ExecuteScalar
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx
Like this:
using(var sqlCon = new SqlConnetion())
{
using(var sqlCommand = sqlCon.CreateCommand())
{
sqlCommand.CommandText = "SELECT COUNT(EMP_CODE) FROM Attendance WHERE Month = #curMonth AND EMP_CODE= #empCode";
command.Parameters.Add("#curMonth", SqlDbType.Int).Value = curMonth;
command.Parameters.Add("#empCode", SqlDbType.Int).Value = 2222;
var count = (int)sqlCommand.ExecuteScalar();
txtPresentDay.Text = Convert.ToString(count);
}
}
I only know little about your database and your requirements, but here a little warning: you are only asking for the month, be sure that is really what you want.
So the attendance will be counted if it was on 2017/5/1, 2016/5/1, 1997/5/1 - since the month is always the same but the year changes.

How to get ID against selected value of Dropdownlist C#

How can I get the ID against the selected value of a DropDownList which is bound with DB?
Then how can I insert this ID into another table?
To get ID code
string query = "Select ID From Table-1 Where Name=" + DropDwonList.SelectedValue;
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
string getId = dr[0].ToString();
DropDownList Binding Code
string query = "Select ID, Name from Table-1";
SqlConnection con = new SqlConnection(conStr);
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
da.Fill(dt);
DropDwonList.DataSource = dt;
DropDwonList.DataTextField = "Name";
DropDwonList.DataValueField = "ID";
DropDwonList.DataBind();
DropDwonList.Items.Insert(0, new ListItem("--Select Name--"));
1) string Id = DropDwonList.SelectedValue;
2) To insert into another table just use a query:
string Id = DropDwonList.SelectedValue;
using (SqlConnection sql = new SqlConnection("Your connection string"))
{
SqlCommand cmd = new SqlCommand();
string query = #"INSERT INTO TABLE2(Column1)
VALUES(" + Id + ")";
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.Connection = sql;
sql.Open();
cmd.ExecuteNonQuery();
sql.Close();
}
You should do it this way because you always ensure that you are closing a connection after using it.

Categories

Resources