how to convert the string to date in grid view that connected to Mysql via object data source.
for CoopF_From and CoopF_To columns.
Convert.ToDateTime "shows the the date and the time, and I want only to show the date"
the code in data access layer
namespace Demo.CoopF
{
public class CoopF
{
public string CoopF_FName { get; set; }
public string CoopF_MName { get; set; }
public string CoopF_LName { get; set; }
public int CoopF_ID { get; set; }
public string CoopF_Mobile { get; set; }
public string CoopF_Email { get; set; }
public string CoopF_From { get; set; }
public string CoopF_To { get; set; }
}
public class CoopFDataAccessLayer
{
public static void UpdateCoop( int CoopF_ID, string CoopF_FName, string CoopF_MName, string CoopF_LName, string CoopF_Mobile, string CoopF_Email, string CoopF_From, string CoopF_To)
{
string CF = "server=localhost; userid=; password=; database=; allowuservariables=True";
using (MySqlConnection connection = new MySqlConnection(CF))
{
string UpdateQuery = " Update coop_female SET CoopF_FName=#CoopF_FName," + " CoopF_MName=#CoopF_MName," + " CoopF_LName=#CoopF_LName," + "CoopF_Mobile=#CoopF_Mobile," + "CoopF_Email=#CoopF_Email,"+ "CoopF_From=#CoopF_From,"+"CoopF_To=#CoopF_To=#CoopF_To WHERE CoopF_ID=#CoopF_ID";
MySqlCommand cmd = new MySqlCommand(UpdateQuery, connection);
cmd.Connection.Open();
MySqlParameter paramCoopF_FName = new MySqlParameter("#CoopF_FName", CoopF_FName);
cmd.Parameters.Add(paramCoopF_FName);
MySqlParameter paramCoopF_MName = new MySqlParameter("#CoopF_MName", CoopF_MName);
cmd.Parameters.Add(paramCoopF_MName);
MySqlParameter paramCoopF_LName = new MySqlParameter("#CoopF_LName", CoopF_LName);
cmd.Parameters.Add(paramCoopF_LName);
MySqlParameter paramCoopF_ID = new MySqlParameter("#CoopF_ID", CoopF_ID);
cmd.Parameters.Add(paramCoopF_ID);
MySqlParameter paramCoopF_Mobile = new MySqlParameter("#CoopF_Mobile", CoopF_Mobile);
cmd.Parameters.Add(paramCoopF_Mobile);
MySqlParameter paramCoopF_Email = new MySqlParameter("#CoopF_Email", CoopF_Email);
cmd.Parameters.Add(paramCoopF_Email);
MySqlParameter paramCoopF_From = new MySqlParameter("#CoopF_From", Convert.ToDateTime(CoopF_From));
cmd.Parameters.Add(paramCoopF_From);
MySqlParameter paramCoopF_To = new MySqlParameter("#CoopF_To", Convert.ToDateTime(CoopF_To));
cmd.Parameters.Add(paramCoopF_To);
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
public static List<CoopF> GetAllEmployees()
{
List<CoopF> listCoopF = new List<CoopF>();
string CF = "server=localhost; userid=; password=; database=; allowuservariables=True";
using (MySqlConnection connection = new MySqlConnection(CF))
{
MySqlCommand cmd = new MySqlCommand("Select * from coop_female", connection);
connection.Open();
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
CoopF coop = new CoopF();
coop.CoopF_FName = rdr["CoopF_FName"].ToString();
coop.CoopF_MName = rdr["CoopF_MName"].ToString();
coop.CoopF_LName = rdr["CoopF_LName"].ToString();
coop.CoopF_ID = Convert.ToInt32(rdr["CoopF_ID"]);
coop.CoopF_Mobile = rdr["CoopF_Mobile"].ToString();
coop.CoopF_Email = rdr["CoopF_Email"].ToString();
coop.CoopF_From = rdr["CoopF_From"].ToString();
coop.CoopF_To= rdr["CoopF_To"].ToString();
listCoopF.Add(coop);
}
}
return listCoopF;
}
public static void DeleteCoop(int CoopF_ID)
{
string CF = "server=localhost; userid=; password=; database=; allowuservariables=True";
using (MySqlConnection connection = new MySqlConnection(CF))
{
string UpdateQuery = " Delete from Coop_female WHERE CoopF_ID=#CoopF_ID";
MySqlCommand cmd = new MySqlCommand(UpdateQuery, connection);
MySqlParameter param = new MySqlParameter("#CoopF_ID", CoopF_ID);
cmd.Parameters.Add(param);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
public static void InsertCoop(string CoopF_FName, string CoopF_MName, string CoopF_LName, int CoopF_ID, string CoopF_Mobile, string CoopF_Email, string CoopF_From, string CoopF_To)
{
string CF = "server=localhost; userid=; password=; database=; allowuservariables=True";
using (MySqlConnection connection = new MySqlConnection(CF))
{
string UpdateQuery = " INSERT INTO Coop_female (CoopF_FName, CoopF_Mname, CoopF_LName, CoopF_ID, CoopF_Mobile, CoopF_Email, CoopF_From, CoopF_To)" + " VALUES (#CoopF_FName,#CoopF_MName,#CoopF_LName,#CoopF_ID,#CoopF_Mobile,#CoopF_Email,#CoopF_From,#CoopF_To)";
MySqlCommand cmd = new MySqlCommand(UpdateQuery, connection);
MySqlParameter paramCoopF_FName = new MySqlParameter("#CoopF_FName", CoopF_FName);
cmd.Parameters.Add(paramCoopF_FName);
MySqlParameter paramCoopF_MName = new MySqlParameter("#CoopF_MName", CoopF_MName);
cmd.Parameters.Add(paramCoopF_MName);
MySqlParameter paramCoopF_LName = new MySqlParameter("#CoopF_LName", CoopF_LName);
cmd.Parameters.Add(paramCoopF_LName);
MySqlParameter paramCoopF_ID = new MySqlParameter("#CoopF_ID", CoopF_ID);
cmd.Parameters.Add(paramCoopF_ID);
MySqlParameter paramCoopF_Mobile = new MySqlParameter("#CoopF_Mobile", CoopF_Mobile);
cmd.Parameters.Add(paramCoopF_Mobile);
MySqlParameter paramCoopF_Email = new MySqlParameter("#CoopF_Email", CoopF_Email);
cmd.Parameters.Add(paramCoopF_Email);
MySqlParameter paramCoopF_From = new MySqlParameter("#CoopF_From", Convert.ToDateTime(CoopF_From));
cmd.Parameters.Add(paramCoopF_From);
MySqlParameter paramCoopF_To = new MySqlParameter("#CoopF_To", Convert.ToDateTime(CoopF_To));
cmd.Parameters.Add(paramCoopF_To);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
}
}
in code behind
protected void lbInsert_Click(object sender, EventArgs e)
{
ObjectDataSource1.InsertParameters["CoopF_FName"].DefaultValue=((TextBox)GridView1.FooterRow.FindControl("TxtFName")).Text;
ObjectDataSource1.InsertParameters["CoopF_MName"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("TxtMName")).Text;
ObjectDataSource1.InsertParameters["CoopF_LName"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("TxtLName")).Text;
ObjectDataSource1.InsertParameters["CoopF_ID"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("TxtID")).Text;
ObjectDataSource1.InsertParameters["CoopF_Mobile"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("TxtMobile")).Text;
ObjectDataSource1.InsertParameters["CoopF_Email"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("TxtEmail")).Text;
ObjectDataSource1.InsertParameters["CoopF_From"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("TxtFrom")).Text;
ObjectDataSource1.InsertParameters["CoopF_To"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("TxtTo")).Text;
ObjectDataSource1.Insert();
}
You can use following :
Convert.ToDateTime(CoopF_From).Date;
It will give you the Date value only
As I see it, you need to represent DateTime values as strings containing only the date part. There is a standard format specifier for this, namely "d".
The following interactive C# session illustrates the difference between ToString() and ToString("d").
> DateTime.Now.ToString()
"2017-01-07 18:13:00"
> DateTime.Now.ToString("d")
"2017-01-07"
More info
Related
I have inserted an image on the 1st form namely Add_Staff and want to get that image on the 2nd form namely Staff_Detail's data gridview. how I can pass reference of add_staff images to staff_detail form's data gridview. Here is the code.
Insertion Code: -
private void BTNSTAFF_Click(object sender, EventArgs e)
{
if (staffid.Text == "")
{
if (teachername.Text == "" || saddress.Text == "" || semail.Text == "" || contact.Text == "" || jobspeciality.Text == "")
{
MessageBox.Show("All Fields Required");
}
else
{
Image pimg = pictureBox1.Image;
ImageConverter converter = new ImageConverter();
var ImageConvert = converter.ConvertTo(pimg, typeof(byte[]));
conn.Open();
//Values Inserted into Course
SqlCommand cmd = new SqlCommand("insert into staff values (#a,#b,#c,#d,#e,#g)", conn);
cmd.Parameters.AddWithValue("#a", teachername.Text);
cmd.Parameters.AddWithValue("#b", saddress.Text);
cmd.Parameters.AddWithValue("#c", semail.Text);
cmd.Parameters.AddWithValue("#d", contact.Text);
cmd.Parameters.AddWithValue("#e", jobspeciality.Text);
cmd.Parameters.AddWithValue("#g", ImageConvert);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Inserted");
frm1.RefreshGrid();
conn.Close();
Staff_Clear();
this.Hide();
}
}}
Staff Detail Code for View Deatil: -
public partial class Staff_Detail : Form
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\mudas\source\repos\WindowsFormsApp1\WindowsFormsApp1\WindowsFormsApp1\Database1.mdf;Integrated Security=True");
public static string column_id = "";
public static string column_name = "";
public static string column_address = "";
public static string column_email = "";
public static string column_contact = "";
public static string column_job = "";
public Staff_Detail()
{
InitializeComponent();
View();
}
public void View()
{
try
{
dataGridView4.Rows.Clear();
// if (conn.State != ConnectionState.Open)
conn.Open();
SqlCommand cmd = new SqlCommand("Select * From staff", conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
String column_getid = dr["id"].ToString();
String column_getname = dr["name"].ToString();
String column_getaddress = dr["address"].ToString();
String column_getemail = dr["email"].ToString();
String column_getcontact = dr["contact"].ToString();
String column_getjob = dr["job"].ToString();
dataGridView4.Rows.Add(column_getid, column_getname, column_getaddress, column_getemail, column_getcontact, column_getjob, "Edit/Delet");
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void dataGridView4_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
int rowIndex = dataGridView4.CurrentCell.RowIndex;
String Column_id = dataGridView4.Rows[rowIndex].Cells[0].Value.ToString();
String Column_name = dataGridView4.Rows[rowIndex].Cells[1].Value.ToString();
String Column_address = dataGridView4.Rows[rowIndex].Cells[2].Value.ToString();
String Column_email = dataGridView4.Rows[rowIndex].Cells[3].Value.ToString();
String Column_contact = dataGridView4.Rows[rowIndex].Cells[4].Value.ToString();
String Column_job = dataGridView4.Rows[rowIndex].Cells[5].Value.ToString();
column_id = Column_id;
column_name = Column_name;
column_address = Column_address;
column_email = Column_email;
column_contact = Column_contact;
column_job = Column_job;
Add_Staff ad = new Add_Staff(this);
ad.Show();
ad.BringToFront();
}
}
I'm trying to write a CRUD app and I have a problem with the Create method. Program is crashing with error
System.Data.SqlClient.SqlException: 'Violation of PRIMARY KEY constraint 'PK_Pracownicy'. Cannot insert duplicate key in object 'dbo.Pracownicy'. The duplicate key value is (11).
The statement has been terminated.'
But I can see in my SQL Server that this position is added to Pracownicy table, so I don't know where is a problem. Its look like the error is generated after I put new values to table
class SqlHelper
{
public int RowsLenght { get; set; }
private SqlConnection sqlConnection;
public string Command { get; set; }
public SqlHelper(string connectionString)
{
sqlConnection = new SqlConnection(connectionString);
sqlConnection.Open();
}
public int Create(string command, SqlParameter []parameters)
{
//wykonanie polecenia na bazie
using var cmd = new SqlCommand(command, sqlConnection);
cmd.Parameters.AddRange(parameters);
ShowTable(cmd);
return cmd.ExecuteNonQuery();
}
public int Read(string command)
{
//wykonanie polecenia na bazie
using var cmd = new SqlCommand(command, sqlConnection);
ShowTable(cmd);
return cmd.ExecuteNonQuery();
}
private int ShowTable(SqlCommand command)
{
var reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetInt32(0) + "\t" + reader.GetString(2) + " " +
reader.GetString(1) + "\t" + reader.GetString(3));
RowsLenght++;
}
reader.Close();
return RowsLenght;
}
}
class Program
{
static void Main()
{
SqlConnectionStringBuilder connectionString = new SqlConnectionStringBuilder
{
DataSource = #"HAL\MSSERVER",
InitialCatalog = "ZNorthwind",
IntegratedSecurity = true,
ConnectTimeout = 30,
Encrypt = false,
TrustServerCertificate = false,
ApplicationIntent = 0,
MultiSubnetFailover = false
};
var connectionS = connectionString.ConnectionString;
SqlHelper sql = new SqlHelper(connectionS);
var command = "SELECT * FROM dbo.Pracownicy";
sql.Read(command);
command = "INSERT INTO dbo.Pracownicy (IDpracownika, Nazwisko, ImiÄ™, Stanowisko) VALUES (#IDpracownika, #Nazwisko, #Imie, #Stanowisko)";
var parameters = SetUpParameters(sql.RowsLenght);
sql.Create(command, parameters);
}
private static SqlParameter[] SetUpParameters(int lenght)
{
//inicjalizacja zmiennych:
Console.WriteLine("Podaj imie nowego pracownika: ");
var fname = Console.ReadLine();
Console.WriteLine("Podaj nazwisko pracownika: ");
var lname = Console.ReadLine();
Console.WriteLine("Podaj stanowisko pracownika: ");
var position = Console.ReadLine();
SqlParameter []param = new SqlParameter[4];
param[0] = new SqlParameter("IDpracownika", lenght + 1);
param[1] = new SqlParameter("Imie", fname);
param[2] = new SqlParameter("Nazwisko", lname);
param[3] = new SqlParameter("Stanowisko", position);
return param;
}
}
Thanks
I have this function, which updates some info in my database. It works properly until bool[] days = new bool[7]; and it throws exception message - 'index is outside the bounds of the array'. I cannot understand how it is out of bounds, when I just declared and initialized it.
public static void UpdateDepartment(Department department, string oldName)
{
if (department!=null)
{
try
{
using (MySqlConnection conn = new MySqlConnection(ConnectionString))
{
string query = "select * from people where department = #oldName";
List<User> results = new List<User>();
MySqlCommand cmd_refactor = new MySqlCommand(query, conn);
cmd_refactor.Parameters.AddWithValue("#oldName", oldName);
conn.Open();
MySqlDataReader dataReader = cmd_refactor.ExecuteReader();
while (dataReader.Read())
{
int id = int.Parse(dataReader[0].ToString());
string username = dataReader[1].ToString();
string firstName = dataReader[2].ToString();
string lastName = dataReader[3].ToString();
string email = dataReader[4].ToString();
string phoneNumber = dataReader[5].ToString();
PersonPosition position =
(PersonPosition)Enum.Parse(typeof(PersonPosition), dataReader[6].ToString(), true);
double salary = Double.Parse(dataReader[7].ToString());
Department departmentResult = new Department(dataReader[8].ToString());
ShiftType shiftType =
(ShiftType)Enum.Parse(typeof(ShiftType), dataReader[11].ToString(), true);
bool[] days = new bool[7];
for (int i = 0; i < 7; i++)
{
days[i] = bool.Parse(dataReader[i + 12].ToString());
}
User user = new User(username, firstName, lastName, email, position, salary, shiftType,
days, departmentResult, id, phoneNumber);
results.Add(user);
}
conn.Close();
foreach (var item in results)
{
conn.Open();
item.UserDepartment = department;
UpdateUser(item);
conn.Close();
}
query = "update departments set departmentName = #name where departmentName = #oldName";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("#name", department.Name);
cmd.Parameters.AddWithValue("#oldName", oldName);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
throw new NoConnectionException();
}
}
}
days[i] can't be out of range. It must be the other array in this line which throws this error: dataReader[i + 12]
I'm creating a leave calendar for employees, And for that I'm populating some data onto the calendar using dataset, but it takes too long to load the data.
I'm using multiple MySqlDataReader and connections to read the data from MySql table for each row of the calendar table. Maybe using multiple connections and readers might be the cause of slowing down but I'm not sure. The below is the code I use to populate the data.
class Sample
{
public DateTime Date { get; set; }
public string SlotAvailable { get; set; }
public string Pending { get; set; }
public string HeadCount { get; set; }
}
DateTime firstDate { get; set; }
DateTime lastDate { get; set; }
List<Sample> samples = new List<Sample>();
protected DataSet dsleaveplanner;
protected void FillLeaveplannerDataset()
{
cal2.VisibleDate = cal2.TodaysDate;
DateTime firstDate = new DateTime(cal2.VisibleDate.Year, cal2.VisibleDate.Month, 1).AddDays(-6);
DateTime lastDate = new DateTime(cal2.VisibleDate.Date.AddMonths(1).Year, cal2.VisibleDate.Date.AddMonths(1).Month, 1).AddDays(7);
dsleaveplanner = GetCurrentMonthData(firstDate, lastDate);
}
protected DateTime GetFirstDayOfNextMonth()
{
int monthNumber, yearNumber;
if (cal2.VisibleDate.Month == 12)
{
monthNumber = 1;
yearNumber = cal2.VisibleDate.Year + 1;
}
else
{
monthNumber = cal2.VisibleDate.Month + 1;
yearNumber = cal2.VisibleDate.Year;
}
DateTime lastDate = new DateTime(yearNumber, monthNumber, 1);
return lastDate;
}
protected DataSet GetCurrentMonthData(DateTime firstDate, DateTime lastDate)
{
string site = lblsite.Text;
string skill = lblskill.Text;
string shift = lblshift.Text;
DataSet dsMonth = new DataSet();
string MyConString = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(MyConString);
string caldate = "Select * From setshrinkage Where date >= #firstDate And date <= #lastDate And site=#site And skill=#skill And shift=#shift Group By date";
MySqlCommand cmd = new MySqlCommand(caldate, con);
cmd.Parameters.AddWithValue("#firstDate", firstDate);
cmd.Parameters.AddWithValue("#lastDate", lastDate);
cmd.Parameters.AddWithValue("#site", site);
cmd.Parameters.AddWithValue("#skill", skill);
cmd.Parameters.AddWithValue("#shift", shift);
MySqlDataAdapter mysqlDataAdapter = new MySqlDataAdapter(cmd);
try
{
mysqlDataAdapter.Fill(dsMonth);
con.Close();
}
catch { }
return dsMonth;
}
public void caldisp(DayRenderEventArgs e)
{
Environment.NewLine.ToString();
e.Cell.ForeColor = System.Drawing.Color.Red;
e.Cell.Font.Size = 9;
e.Cell.Controls.Add(new LiteralControl("<p></p>Slot available:"));
e.Cell.Controls.Add(new LiteralControl(samples.Where(x => x.Date == e.Day.Date).FirstOrDefault().SlotAvailable.ToString()));
e.Cell.Controls.Add(new LiteralControl("<p></p>Pending:"));
e.Cell.Controls.Add(new LiteralControl(samples.Where(x => x.Date == e.Day.Date).FirstOrDefault().Pending.ToString()));
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
DateTime nextDate;
//e.Day.IsSelectable = false;
if (dsleaveplanner != null)
{
foreach (DataRow dr in dsleaveplanner.Tables[0].Rows)
{
nextDate = (DateTime)dr["date"];
var hcount = (dr["headCount"].ToString());
Int32 hcount1 = Convert.ToInt32(hcount);
string MyConString = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection conn = new MySqlConnection(MyConString);
string cntdate = "SELECT COUNT(date) FROM approved WHERE date = #date And site=#site And skill=#skill And shift=#shift And status=#status";
string cntdate2 = "SELECT COUNT(date) FROM approved WHERE date = #date And site=#site And skill=#skill And shift=#shift And status=#status";
MySqlCommand cmd2 = new MySqlCommand(cntdate, conn);
MySqlCommand cmd3 = new MySqlCommand(cntdate2, conn);
cmd2.Parameters.AddWithValue("#date", nextDate);
cmd2.Parameters.AddWithValue("#site", lblsite.Text);
cmd2.Parameters.AddWithValue("#skill", lblskill.Text);
cmd2.Parameters.AddWithValue("#shift", lblshift.Text);
cmd2.Parameters.AddWithValue("#status", "auto-approved");
cmd3.Parameters.AddWithValue("#date", nextDate);
cmd3.Parameters.AddWithValue("#site", lblsite.Text);
cmd3.Parameters.AddWithValue("#skill", lblskill.Text);
cmd3.Parameters.AddWithValue("#shift", lblshift.Text);
cmd3.Parameters.AddWithValue("#status", "pending");
string chklog = "SELECT date FROM approved WHERE date = #date And agentlogin=#login And status=#stat";
MySqlCommand cmd1 = new MySqlCommand(chklog, conn);
cmd1.Parameters.AddWithValue("#date", nextDate);
cmd1.Parameters.AddWithValue("#login", Label1.Text);
cmd1.Parameters.AddWithValue("#stat", "auto-approved");
conn.Open();
string count = cmd2.ExecuteScalar().ToString();
string count2 = cmd3.ExecuteScalar().ToString();
var slot2 = Convert.ToInt32(count);
Int32 slot3 = hcount1 - slot2;
string slot4 = slot3.ToString();
MySqlDataReader dr1 = cmd1.ExecuteReader();
MySqlConnection con = new MySqlConnection(MyConString);
string chklog1 = "SELECT date FROM approved WHERE date = #date And agentlogin=#login And status=#stat";
MySqlCommand cmd4 = new MySqlCommand(chklog1, con);
cmd4.Parameters.AddWithValue("#date", nextDate);
cmd4.Parameters.AddWithValue("#login", Label1.Text);
cmd4.Parameters.AddWithValue("#stat", "pending");
con.Open();
MySqlDataReader dr2 = cmd4.ExecuteReader();
MySqlConnection con2 = new MySqlConnection(MyConString);
string chklog2 = "SELECT date FROM approved WHERE date = #date And agentlogin=#login And status=#stat";
MySqlCommand cmd5 = new MySqlCommand(chklog2, con2);
cmd5.Parameters.AddWithValue("#date", nextDate);
cmd5.Parameters.AddWithValue("#login", Label1.Text);
cmd5.Parameters.AddWithValue("#stat", "rejected");
con2.Open();
MySqlDataReader dr3 = cmd5.ExecuteReader();
MySqlConnection con3 = new MySqlConnection(MyConString);
string chklog3 = "SELECT date FROM approved WHERE date = #date And agentlogin=#login And status=#stat";
MySqlCommand cmd6 = new MySqlCommand(chklog3, con3);
cmd6.Parameters.AddWithValue("#date", nextDate);
cmd6.Parameters.AddWithValue("#login", Label1.Text);
cmd6.Parameters.AddWithValue("#stat", "agent-withdrawn");
con3.Open();
MySqlDataReader dr4= cmd6.ExecuteReader();
if (nextDate == e.Day.Date)
{
if (dr1.HasRows)
{
e.Cell.BackColor = System.Drawing.Color.LightGreen;
}
else if (dr2.HasRows)
{
e.Cell.BackColor = System.Drawing.Color.Gold;
}
else if (dr3.HasRows)
{
e.Cell.BackColor = System.Drawing.Color.Tomato;
}
else if (dr4.HasRows)
{
e.Cell.BackColor = System.Drawing.Color.DarkTurquoise;
}
}
conn.Close();
con.Close();
con2.Close();
con3.Close();
samples.Add(new Sample { Date = nextDate, SlotAvailable = slot4, Pending = count2 });
}
if (samples.Any(x => x.Date == e.Day.Date))
{
string weekoff = lblweekoff.Text;
List<string> offday = (lblweekoff.Text).Split(',').ToList();
if (offday.Contains(e.Day.Date.ToString("ddd")))
{
e.Cell.Font.Size = 9;
e.Cell.Controls.Add(new LiteralControl("<p>Week-Off </p>"));
}
else
{
caldisp(e);
}
}
else
{
e.Cell.ForeColor = System.Drawing.Color.Red;
e.Cell.Font.Size = 9;
e.Cell.Controls.Add(new LiteralControl("<p>Target not set! </p>"));
}
}
}
How can I make this process faster? Any help is appreciated, Thanks in advance!
You have 6 SQL queries into foreach statement, if you have 10 rows in dsleaveplanner the program will execute 60 SQL queries. this number of SQL queries will have a negative impact on performance.
try to retrieve all data before your foreach statement and stock data into lists (memory) then use it within your foreach
Im using this code to do display images to edit:
protected void Repeater_Outer_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
RepeaterItem item = e.Item;
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
Repeater Inner = (Repeater)item.FindControl("image_Repeater");
HiddenField Inner_Id = (HiddenField)item.FindControl("HiddenField_Id");
MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["dbcnx"].ToString());
MySqlCommand cmdNew = new MySqlCommand();
cmdNew.Connection = conn;
cmdNew.Parameters.AddWithValue("#id", Inner_Id.Value);
cmdNew.CommandText = "SELECT * FROM images WHERE FK_album = #id";
conn.Open();
Inner.DataSource = cmdNew.ExecuteReader();
Inner.DataBind();
Label Label_Amount = (Label)item.FindControl("Label_Amount");
Label_Amount.Text = Convert.ToString(Inner.Items.Count);
conn.Close();
}
}
My problem is that each time the repeater runs it connects to the database which makes the page take really long to load (like 10 seconds)
So i want to populate a dataset or a generic List to databind instead. I've tried this:
protected static List<string> dataSetImages(){
MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["dbcnx"].ToString());
string sql = "select * from images";
MySqlCommand cmd = new MySqlCommand( sql, conn);
conn.Open();
MySqlDataAdapter sqlDataAdapter = new MySqlDataAdapter(cmd);
DataSet dataSet = new DataSet();
sqlDataAdapter.Fill(dataSet);
conn.Close();
List<string> imageList = new List<string>();
for (int i = 0; i <= dataSet.Tables[0].Rows.Count - 1; i++)
{
string id = dataSet.Tables[0].Rows[i].ItemArray[0].ToString();
string img_name = dataSet.Tables[0].Rows[i].ItemArray[1].ToString();
string img_alt = dataSet.Tables[0].Rows[i].ItemArray[2].ToString();
string FK_album = dataSet.Tables[0].Rows[i].ItemArray[3].ToString();
imageList.Add(id);
imageList.Add(img_name);
imageList.Add(img_alt);
imageList.Add(FK_album);
}
return imageList;
}
How can i use this and compare FK_album to Inner_Id.Value?
If you are insistent on using the RowFilter approach, then this is what you are looking for.
string expression = String.Format("FK_album = {0}", Inner_Id.Value);
DataRow[] filteredRows = imageList.Tables[0].Select(expression);
Here is an article on DataView RowFilter Syntax.
better if you can class like below
public class ImageDto
{
public string Id { get; set; }
public string Name { get; set; }
public string Alt { get; set; }
public string FK_album { get; set; }
}
then
protected static List<ImageDto> dataSetImages(){
List<ImageDto> imageList = new List<ImageDto>();
// add items
return imageList;
}
then you can call above method and get list of ImageDto
List<ImageDto> images = dataSetImages();
in your Repeater_Outer_ItemDataBound method you can do as below
Inner.DataSource = images.Where(i=>i.FK_album == Inner_Id.Value).ToList();