I have been trying to implement this link
to my basic ASP.NET calender but I really worried which method(s) do I use? I used this way and nothing works..
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
calendar1.VisibleDate = DateTime.Today;
FillTrainingDataset();
}
protected DataSet dsTraining;
protected void FillTrainingDataset()
{
DateTime firstDate = new DateTime(calendar1.VisibleDate.Year,
calendar1.VisibleDate.Month, 1);
DateTime lastDate = GetFirstDayOfNextMonth();
dsTraining = GetCurrentMonthData(firstDate, lastDate);
}
protected DateTime GetFirstDayOfNextMonth()
{
int monthNumber, yearNumber;
if (calendar1.VisibleDate.Month == 12)
{
monthNumber = 1;
yearNumber = calendar1.VisibleDate.Year + 1;
}
else
{
monthNumber = calendar1.VisibleDate.Month + 1;
yearNumber = calendar1.VisibleDate.Year;
}
DateTime lastDate = new DateTime(yearNumber, monthNumber, 1);
return lastDate;
}
protected DataSet GetCurrentMonthData(DateTime firstDate,
DateTime lastDate)
{
DataSet dsMonth = new DataSet();
ConnectionStringSettings cs;
cs = ConfigurationManager.ConnectionStrings["KKSTechConnectionString"];
String connString = cs.ConnectionString;
SqlConnection dbConnection = new SqlConnection(connString);
String query;
query = "SELECT StartDate, EndDate FROM Tentative_Orders";
SqlCommand dbCommand = new SqlCommand(query, dbConnection);
dbCommand.Parameters.Add(new SqlParameter("#StartDate",
firstDate));
dbCommand.Parameters.Add(new SqlParameter("#EndDate", lastDate));
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(dbCommand);
try
{
sqlDataAdapter.Fill(dsMonth);
}
catch {}
return dsMonth;
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
DateTime nextDate;
if (dsTraining != null)
{
foreach (DataRow dr in dsTraining.Tables[0].Rows)
{
nextDate = (DateTime)dr["StartDate"];
if (nextDate == e.Day.Date)
{
e.Cell.BackColor = System.Drawing.Color.Pink;
}
}
}
}
protected void Calendar1_VisibleMonthChanged(object sender,
MonthChangedEventArgs e)
{
FillTrainingDataset();
}
}
Is there any simple of way of creating method and rendering onto my Calender? This seems pretty long codes to me.. I expect my dates (Start and End) from my DB Table to appear on the Calender.
Related
I'm trying to bind mysql data to asp:calendar but its not working. I need to display the data in mysql table slotavailable column according to the date column. How can I get it into the calendar cells?
<asp:Calendar ID="cal2" runat="server" Width="50%" DayField="Date" OnDayRender="Calendar1_DayRender"
BackColor="Orange" NextMonthText="Next" PrevMonthText="Prev" >
<DayStyle CssClass="days" VerticalAlign="Top" Font-Name="Arial" Height="80px" BackColor="lightYellow" />
<TodayDayStyle BackColor="Orange" />
<OtherMonthDayStyle BackColor="LightGray" ForeColor="DarkGray"/>
</asp:Calendar>
Below would be the cs code to fetch data
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
cal2.VisibleDate = DateTime.Today;
FillLeaveplannerDataset();
}
}
protected void FillLeaveplannerDataset()
{
DateTime firstDate = new DateTime(cal2.VisibleDate.Year, cal2.VisibleDate.Month, 1);
DateTime lastDate = GetFirstDayOfNextMonth();
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)
{
DataSet dsMonth = new DataSet();
MySqlConnection con = new MySqlConnection("Server=localhost;Database=mydb;Uid=myid;Pwd=abc123;");
MySqlCommand cmd = new MySqlCommand("SELECT * FROM dummy WHERE date >= #firstDate AND date < #lastDate", con);
cmd.Parameters.Add(new MySqlParameter("#firstDate", firstDate));
cmd.Parameters.Add(new MySqlParameter("#lastDate", lastDate));
MySqlDataAdapter mysqlDataAdapter = new MySqlDataAdapter(cmd);
try
{
mysqlDataAdapter.Fill(dsMonth);
}
catch { }
return dsMonth;
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
DateTime nextDate;
if (dsleaveplanner != null)
{
foreach (DataRow dr in dsleaveplanner.Tables[0].Rows)
{
nextDate = (DateTime)dr["date"];
var slot = dr["slotavailable"];
if (nextDate == e.Day.Date)
{
e.Cell.BackColor = System.Drawing.Color.Pink;
}
}
}
}
protected void Calendar1_VisibleMonthChanged(object sender,
MonthChangedEventArgs e)
{
FillLeaveplannerDataset();
}
How can get the slot column data into the calendar cell?
You please make sure that your nextDate and e.Day.Date are matches and then change in your code like
e.Cell.Controls can add any text to your cell
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
DateTime nextDate;
if (dsleaveplanner != null)
{
foreach (DataRow dr in dsleaveplanner.Tables[0].Rows)
{
nextDate = (DateTime)dr["date"];
var slot = dr["slotavailable"];
if (nextDate == e.Day.Date)
{
//This is the line where we add slotavailable column data
e.Cell.Controls.Add(new LiteralControl($"<p>{slot}</p>"));
e.Cell.BackColor = System.Drawing.Color.Pink;
}
}
}
}
The output will be
The advantage of e.Cell.Controls you may add html button or span or image or any else as your need
And e.Cell.Controls.Clear(); may help you to clear all controls related to particular cell
Try once may it help you
C# winform application: i added buttons in datagridview in every row for (update,delete). it works fine but when i search data in this gridview the buttons doesn't work on search results.
Here is my code.
namespace MyBusiness
{
public partial class ExpenceDetails : Form
{
public ExpenceDetails()
{
InitializeComponent();
}
private void ExpenceDetails_Load(object sender, EventArgs e)
{
update();
}
DataTable data;
public void update()
{
string connectionstring = null;
SqlConnection cnn;
connectionstring = #"Server=(local)\SQLEXPRESS;Database=mrtraders;Trusted_Connection=True";
cnn = new SqlConnection(connectionstring);
try
{
cnn.Open();
dataGridView1.ColumnCount = 0;
SqlCommand cmd1 = new SqlCommand("SELECT * FROM Expense", cnn);
SqlDataReader reader = cmd1.ExecuteReader();
if (reader.HasRows)
{
data = new DataTable();
data.Load(reader);
dataGridView1.DataSource = data;
}
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
btn.Text = "Update";
btn.UseColumnTextForButtonValue = true;
dataGridView1.Columns.Add(btn);
DataGridViewButtonColumn btn2 = new DataGridViewButtonColumn();
btn2.Text = "Delete";
btn2.UseColumnTextForButtonValue = true;
dataGridView1.Columns.Add(btn2);
cnn.Close();
}
catch (Exception)
{
myMessageBox my = new myMessageBox("Internal Error...");
my.ShowDialog();
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
this.Close();
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 4)
{
if (e.RowIndex >= 0)
{
//// get ExpenseId//// IMP
int id = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value);
string desc = Convert.ToString(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[1].Value);
int am = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[3].Value);
UpdateExpense a = new UpdateExpense(id,desc,am);
a.ShowDialog();
dataGridView1.DataSource = null;
update();
}
}
else if (e.ColumnIndex == 5)
{
if(e.RowIndex >= 0)
{
int id = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value);
string connectionstring = null;
SqlConnection cnn;
connectionstring = #"Server=(local)\SQLEXPRESS;Database=mrtraders;Trusted_Connection=True";
cnn = new SqlConnection(connectionstring);
try
{
cnn.Open();
SqlCommand cmd1 = new SqlCommand("Delete FROM Expense where expenseId = '"+id+"' ", cnn);
cmd1.ExecuteNonQuery();
myMessageBox my = new myMessageBox("Deleted Successfully...");
my.ShowDialog();
dataGridView1.DataSource = null;
cnn.Close();
update();
}
catch (Exception)
{
myMessageBox my = new myMessageBox("Internal Error...");
my.ShowDialog();
}
}
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
DataView dv = new DataView(data);
dv.RowFilter = string.Format("Description like '%{0}%'", textBox1.Text);
dataGridView1.DataSource = dv.Table;
}
}
}
I created a gridview in asp.net which has two columns of DATETIME datatype, when I connected to mysql database to save it within, it shows me an error " Incorrect datetime value: '01/01/2017 00:07:26' for column 'LogInDate_Time' at row 1" in cmd.ExecuteNonQuery(); line
How to solve it?
C#
protected void Page_Load(object sender, EventArgs e)
{
}
protected void LoggedIn(object sender, EventArgs e)
{
CheckBox checkedCheckBox = (sender as CheckBox);
GridViewRow checkedRow = (checkedCheckBox.NamingContainer as GridViewRow);
Label loggedInDateTime = checkedRow.FindControl("lblLoggedInDateTime") as Label;
if (checkedCheckBox.Checked)
{
loggedInDateTime.Text = DateTime.Now.ToString();
}
else
{
loggedInDateTime.Text = "";
}
}
protected void LoggedOut(object sender, EventArgs e)
{
CheckBox checkedCheckBox = (sender as CheckBox);
GridViewRow checkedRow = (checkedCheckBox.NamingContainer as GridViewRow);
Label loggedOutDateTime = checkedRow.FindControl("lblLoggedOutDateTime") as Label;
if (checkedCheckBox.Checked)
{
loggedOutDateTime.Text = DateTime.Now.ToString();
}
else
{
loggedOutDateTime.Text = "";
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
string Attendance_ID = (row.FindControl("lblAttendanceID") as Label).Text;
string Attendance_Name = (row.FindControl("lblAttendanceName") as Label).Text;
string LogInDate_Time = (row.FindControl("lblLoggedInDateTime") as Label).Text;
string LogOutDate_Time = (row.FindControl("lblLoggedOutDateTime") as Label).Text;
InsertData(Attendance_ID, Attendance_Name, LogInDate_Time, LogOutDate_Time);
}
lblMessage.Text = "All Records Saved Successfully!!";
}
public void InsertData(string Attendance_ID, string Attendance_Name, string LogInDate_Time, string LogOutDate_Time)
{
//Your saving code.
string A = "server=localhost; userid=; password=; database=admindb; allowuservariables=True; Convert Zero Datetime=True; Allow Zero Datetime=True ";
using (MySqlConnection connection = new MySqlConnection(A))
{
string UpdateQuery = " INSERT INTO Attendance_Table (Attendance_ID, Attendance_Name,LogInDate_Time, LogOutDate_Time)" + " VALUES (#Attendance_ID,#Attendance_Name,#LogInDate_Time,#LogOutDate_Time)";
MySqlCommand cmd = new MySqlCommand(UpdateQuery, connection);
MySqlParameter paramAttendance_ID = new MySqlParameter("#Attendance_ID", Attendance_ID);
cmd.Parameters.Add(paramAttendance_ID);
MySqlParameter paramAttendance_Name = new MySqlParameter("#Attendance_Name", Attendance_Name);
cmd.Parameters.Add(paramAttendance_Name);
MySqlParameter paramLogInDate_Time = new MySqlParameter("#LogInDate_Time", LogInDate_Time);
cmd.Parameters.Add(paramLogInDate_Time);
MySqlParameter paramLogOutDate_Time = new MySqlParameter("#LogOutDate_Time", LogOutDate_Time);
cmd.Parameters.Add(paramLogOutDate_Time);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
protected void lbInsert_Click(object sender, EventArgs e)
{
ObjectDataSource1.InsertParameters["Attendance_ID"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("TxtID")).Text;
ObjectDataSource1.InsertParameters["Attendance_Name"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("TxtName")).Text;
ObjectDataSource1.InsertParameters["Attendance_Con"].DefaultValue = ((CheckBox)GridView1.FooterRow.FindControl("cbAttendanceCon")).Text;
ObjectDataSource1.InsertParameters["LogInDate_Time"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtLogIn")).Text;
ObjectDataSource1.InsertParameters["Leaving_Con"].DefaultValue = ((CheckBox)GridView1.FooterRow.FindControl("cbLeavingCon")).Text;
ObjectDataSource1.InsertParameters["LogOutDate_Time"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtLogOut")).Text;
ObjectDataSource1.Insert();
}
}
MySQL wants date in YYYY-MM-DD format.
Reference:
https://dev.mysql.com/doc/refman/5.5/en/datetime.html
friends i'm using class and ado.net
i'm using data table connection oledb and so on
when I take instance of this class using form load to load data on a form control like text box and combo and so on
i do some operation using this instance like add record delete record edit record
i have also navigation button move2first move2last and so on
what is my problem:
my problem when do insert delete update on this instance of class this changes not reflect on the instance it self
when moving using button move i see the same record
how to update the instance of class to reflect the changes
this is class
class dataConnection
{
public int affectedrecord;
//Microsoft.Jet.OLEDB.4.0
public OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Properties.Settings.Default.dPath + ";Jet OLEDB:Database Password=azouz(2016)");
OleDbDataAdapter da;
DataTable dt =new DataTable() ;
OleDbCommand com;
int intRow = 0;
DataRow r;
public DataTable loadingdata(string sql)
{
dt.Clear();
da = new OleDbDataAdapter(sql, cn);
da.Fill(dt);
return dt;
}
public void saverecord(string sql,string[]para,string[]val)
{
cn.Open();
com = new OleDbCommand();
com.CommandText = sql;
com.Connection = cn;
com.CommandType = CommandType.Text;
for (int i = 0; i< para.Count(); i++)
{
com.Parameters.AddWithValue(para[i], val[i]);
}
affectedrecord = com.ExecuteNonQuery();
if (affectedrecord > 0)
{
affectedrecord = 1;
}
cn.Close();
}
public void EditRecord(string sql, string [] para,string []val)
{
cn.Open();
com = new OleDbCommand();
com.CommandText = sql;
com.Connection = cn;
com.CommandType = CommandType.Text;
int x = para.Count();
for (int i = 0; i < para.Count(); i++)
{
com.Parameters.AddWithValue(para[i], val[i]);
}
affectedrecord = com.ExecuteNonQuery();
if (affectedrecord > 0)
{
affectedrecord = 1;
}
cn.Close();
}
public void DeleteRecord(string sql,string [] para,string []val)
{
cn.Open();
com = new OleDbCommand();
com.CommandText = sql;
com.Connection = cn;
com.CommandType = CommandType.Text;
for (int i =0;i<1;i++)
{
com.Parameters.AddWithValue(para[i], val[i]);
}
affectedrecord = com.ExecuteNonQuery();
if (affectedrecord > 0)
{
affectedrecord = 1;
}
cn.Close();
}
operation on form
public partial class frmRegStore : Window
{
public frmRegStore()
{
InitializeComponent();
}
#region Variables
// 'هذا النموذج يعتمد علي
//' class
//' c worktable
//'لملئ النموذج وورقة البيانات بالسجلات
//'تعريف كائن من الكلاس
dataConnection TotalWork = new dataConnection();
DataTable dt = new DataTable();
DataRow r;
#endregion
private void btnSave_Click(object sender, RoutedEventArgs e)
{
string[] para = { "#storeName" };
string[] val = { this.txtStoreName.Text };
dataConnection Stores = new dataConnection();
Stores.saverecord("insert into Stores (StoreName)values(?);", para, val);
if (Stores.affectedrecord > 0)
{
MessageBox.Show("تم اضافة السجل بنجاح");
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
dt = TotalWork.loadingdata("Select * from Stores");
r = TotalWork.Move2First();
showData();
}
public void showData()
{
if ((r != null))
{
this.txtStoreID.Text = r[0].ToString();
this.txtStoreName.Text = r[1].ToString();
}
}
private void btnLast_Click(object sender, RoutedEventArgs e)
{
r = TotalWork.Move2Last();
showData();
}
private void btnNext_Click(object sender, RoutedEventArgs e)
{
r = TotalWork.Move2Next();
showData();
}
private void btnPrevious_Click(object sender, RoutedEventArgs e)
{
r = TotalWork.Move2Previous();
showData();
}
private void btnFirst_Click(object sender, RoutedEventArgs e)
{
r = TotalWork.Move2First();
showData();
}
private void btnDelete_Click(object sender, RoutedEventArgs e)
{
string[] para = { "#storeID" };
string[] val = { this.txtStoreID.Text };
dataConnection Stores = new dataConnection();
Stores.saverecord("Delete from Stores where StoreId =?", para, val);
if (Stores.affectedrecord > 0)
{
MessageBox.Show("تم حذف السجل بنجاح");
}
}
private void btnEdit_Click(object sender, RoutedEventArgs e)
{
string[] para = {"#storeName", "#storeID" };
string[] val = { this.txtStoreName.Text,this.txtStoreID.Text };
dataConnection Stores = new dataConnection();
Stores.saverecord("update Stores set StoreName = #storeName where StoreId =#storeID", para, val);
if (Stores.affectedrecord > 0)
{
MessageBox.Show("تم تعديل السجل بنجاح");
}
}
}
}
I want to display the date which is selected in another form using monthCalender control..
Here is my code..
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
ActivityScheduler frm1 = new ActivityScheduler();
frm1.Show();
}
private void ActivityScheduler_Load(object sender, EventArgs e)
{
if (con.State == ConnectionState.Open) { con.Close(); }
con.Open();
RemainderPopUp frm = new RemainderPopUp();
string s = "select * from [Activity_Scheduler]";
SqlCommand sCmd = new SqlCommand(s, con);
SqlDataAdapter da = new SqlDataAdapter(sCmd);
DataSet ds = new DataSet();
da.Fill(ds, "[Activity_Scheduler]");
datagridActivityScheduler.DataSource = ds.Tables[0];
datagridActivityScheduler.AllowUserToAddRows = true;
DataTable dt = new DataTable();
dt = ds.Tables["Activity_Scheduler"];
if (dt == null)
{
datagridActivityScheduler.Rows[0].Cells[3].Value = frm.monthCalendar1.SelectionRange.Start.ToShortDateString();
MessageBox.Show(datagridActivityScheduler.Rows[0].Cells[3].Value.ToString());
}
con.Close();
}
It is displaying the correct value in messagebox..but the value is not displaying in datagridview...
Plz anybody help me out..
Try Following Code :
form_load()
{
private string myDate="1999/12/12";
// Declare a Date property of type string:
public string Name
{
get
{
return myDate;
}
set
{
myName = value;
}
}
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
ActivityScheduler frm1 = new ActivityScheduler();
ActivityScheduler.myDate = frm.monthCalendar1.SelectionRange.Start.ToShortDateString()
frm1.Show();
}
Now you can get date on other form as :
string myDate = frm1.myDate();
Let me know if any queries.