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
Related
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
I worked on asp web page that have a dropdown of semester names, and according to the selected item from this dropdown a gridview of levels and courses will appear.
The problem is that grid view never change according to the drop down selection
So when i choose a semester name let's say "Fall", the gridview shows all semesters " Fall & Spring & Summer" with their levels and courses.
Here is my code:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gvSemester.DataSource = GetData(string.Format("select COURSE_SEMESTER from COURSE GROUP BY COURSE_SEMESTER"));
gvSemester.DataBind();
}
}
private static DataTable GetData(string query)
{
string constr = ConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString;
using (OracleConnection con = new OracleConnection(constr))
{
using (OracleCommand cmd = new OracleCommand())
{
cmd.CommandText = query;
using (OracleDataAdapter sda = new OracleDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
}
}
}
protected void Show_Hide_LevelsGrid(object sender, EventArgs e)
{
ImageButton imgShowHide = (sender as ImageButton);
GridViewRow row = (imgShowHide.NamingContainer as GridViewRow);
if (imgShowHide.CommandArgument == "Show")
{
row.FindControl("pnlLevels").Visible = true;
imgShowHide.CommandArgument = "Hide";
imgShowHide.ImageUrl = "~/image/minus.png";
string semesterId = gvSemester.DataKeys[row.RowIndex].Value.ToString();// semester
GridView gvLevel = row.FindControl("gvLevel") as GridView;
BindLevels(semesterId, gvLevel);
}
else
{
row.FindControl("pnlLevels").Visible = false;
imgShowHide.CommandArgument = "Show";
imgShowHide.ImageUrl = "~/image/plus.png";
}
}
private void BindLevels(string semesterId, GridView gvLevel)
{
gvLevel.ToolTip = semesterId;
gvLevel.DataSource = GetData(string.Format("SELECT COURSE_LEVEL from COURSE where COURSE_SEMESTER= '" + semesterId + "' GROUP BY COURSE_LEVEL ORDER BY COURSE_LEVEL")); //was COURSE_SEMESTER=Check it shows the selected semester levels for all
gvLevel.DataBind();
}
protected void Show_Hide_CoursesGrid(object sender, EventArgs e)
{
ImageButton imgShowHide = (sender as ImageButton);
GridViewRow row = (imgShowHide.NamingContainer as GridViewRow);
if (imgShowHide.CommandArgument == "Show")
{
row.FindControl("pnlCourses").Visible = true;
imgShowHide.CommandArgument = "Hide";
imgShowHide.ImageUrl = "~/image/minus.png";
string levelId = (row.NamingContainer as GridView).DataKeys[row.RowIndex].Value.ToString();//level
GridView gvCourse = row.FindControl("gvCourse") as GridView;//..
BindCourses(levelId, gvCourse);//..
}
else
{
row.FindControl("pnlCourses").Visible = false;
imgShowHide.CommandArgument = "Show";
imgShowHide.ImageUrl = "~/image/plus.png";
}
}
private void BindCourses(string levelId, GridView gvCourse)
{
gvCourse.ToolTip = levelId;
gvCourse.DataSource = GetData(string.Format("select * from COURSE where COURSE_LEVEL='{0}'", levelId));
gvCourse.DataBind();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
You can set your dropdown list AutoPostBack = True.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
BindLevels();
}
fill your gridview with dropdown SelectedIndexChanged event and apply where condition in your SQL query.
Add Update Panel for the "levels and courses" grid.
At the dropdown Change event , you update the grid.
UpdatePanelId.Update();
I have multiple dropdownlist box all querying the same column, same table and from the same database. For example under memberID column i have the following IDs.
12345
23456
34567
And i have 3 different dropdownlist box as shown below
<asp:DropDownList ID="memberID3" runat="server" Visible="false" OnSelectedIndexChanged="ddlpid3_SelectedIndexChanged" >
</asp:DropDownList>
<asp:DropDownList ID="memberID1" runat="server" Visible="false" OnSelectedIndexChanged="ddlpid1_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="memberID2" runat="server" Visible="false" OnSelectedIndexChanged="ddlpid2_SelectedIndexChanged">
</asp:DropDownList>
I added update panel between the dropdownlist so as to allow my dropdownlist to refresh upon any updates/selections.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
</ContentTemplate>
</asp:UpdatePanel>
For instance, when memberID1 selected 12345, the other 2 dropdownlist (memberID2 and 3) will not display the ID 12345. Vice versa, when memberID1 select the default value of the dropdownlist, the ID reappears in the other 2 dropdownlistbox. I have added a default value for all of the DDL.
memeberID(number).Items.Insert(0, new ListItem(" Please select a Member ID", ""));
memeberID(number).SelectedIndex = 0;
If i have not mistaken the property of update panel, isn't that able to make this function work?
here is the binding code as requested.
protected void ddllocation_SelectedIndexChanged(object sender, EventArgs e)
{
using (var connAdd = new SqlConnection("Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI"))
{
connAdd.Open();
var sql = "Select policeid from PoliceAccount where status ='available' and handle ='offcase' and postedto='" + ddllocation.SelectedValue + "'";
using (var cmdAdd = new SqlDataAdapter(sql, connAdd))
{
DataSet ds2 = new DataSet();
cmdAdd.Fill(ds2);
memberID1.Items.Clear();
memberID1.DataSource = ds2;
memberID1.DataTextField = "memberID";
memberID1.DataValueField = "memberID";
memberID1.DataBind();
memberID1.Items.Insert(0, new ListItem("Please select a Member ID", ""));
memberID1.SelectedIndex = 0;
memberID2.Items.Clear();
memberID2.DataSource = ds2;
memberID2.DataTextField = "memberID";
memberID2.DataValueField = "memberID";
memberID2.DataBind();
memberID2.Items.Insert(0, new ListItem("Please select a Member ID", ""));
memberID2.SelectedIndex = 0;
memberID3.Items.Clear();
memberID3.DataSource = ds2;
memberID3.DataTextField = "memberID";
memberID3.DataValueField = "memberID";
memberID3.DataBind();
memberID3.Items.Insert(0, new ListItem("Please select a Member ID", ""));
memberID3.SelectedIndex = 0;
}
UPDATE
For now i'm able to allow my other ddl to re-bind and cache the selected value in the other dropdownlist when the default value is selected. However, when i select other ID, the ID are being removed and it wont re-bind the other ddl.
protected void FillddlLocations()
{
FillDropdown(ddlpid1);
FillDropdown(ddlpid2);
FillDropdown(ddlpid3);
FillDropdown(ddlpid4);
FillDropdown(ddlpid5);
ddlpid1.Visible = false;
ddlpid2.Visible = false;
ddlpid3.Visible = false;
ddlpid4.Visible = false;
ddlpid5.Visible = false;
}
protected void FillDropdown(DropDownList ddl)
{
using (var connAdd = new SqlConnection("Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI"))
{
connAdd.Open();
var sql = "Select policeid from PoliceAccount where status ='available' and handle ='offcase' and postedto='" + ddllocation.SelectedValue + "'";
using (var cmdAdd = new SqlDataAdapter(sql, connAdd))
{
DataSet ds2 = new DataSet();
cmdAdd.Fill(ds2);
ddl.Items.Clear();
ddl.DataSource = ds2;
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("Police ID", ""));
ddl.SelectedIndex = 0;
}
}
}
protected void ddlpid1_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlpid1.SelectedIndex > 0)
{
Session["pid1"] = ddlpid1.SelectedValue;
ListItem removeItem2 = ddlpid2.Items.FindByValue(ddlpid1.SelectedValue);
ddlpid2.Items.Remove(removeItem2);
ListItem removeItem3 = ddlpid3.Items.FindByValue(ddlpid1.SelectedValue);
ddlpid3.Items.Remove(removeItem3);
ListItem removeItem4 = ddlpid4.Items.FindByValue(ddlpid1.SelectedValue);
ddlpid4.Items.Remove(removeItem4);
ListItem removeItem5 = ddlpid5.Items.FindByValue(ddlpid1.SelectedValue);
ddlpid5.Items.Remove(removeItem5);
}
else
if (ddlpid1.SelectedItem.Text.Equals("Police ID"))
{
FillDropdown(ddlpid1);
FillDropdown(ddlpid2);
FillDropdown(ddlpid3);
FillDropdown(ddlpid4);
FillDropdown(ddlpid5);
ddlpid2.SelectedValue = (String)Session["pid2"];
ddlpid2_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid3.SelectedValue = (String)Session["pid3"];
ddlpid3_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid4.SelectedValue = (String)Session["pid4"];
ddlpid4_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid5.SelectedValue = (String)Session["pid5"];
ddlpid5_SelectedIndexChanged(this, EventArgs.Empty);
}
}
protected void ddlpid2_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlpid2.SelectedIndex > 0)
{
Session["pid2"] = ddlpid2.SelectedValue;
ListItem removeItem1 = ddlpid1.Items.FindByValue(ddlpid2.SelectedValue);
ddlpid1.Items.Remove(removeItem1);
ListItem removeItem3 = ddlpid3.Items.FindByValue(ddlpid2.SelectedValue);
ddlpid3.Items.Remove(removeItem3);
ListItem removeItem4 = ddlpid4.Items.FindByValue(ddlpid2.SelectedValue);
ddlpid4.Items.Remove(removeItem4);
ListItem removeItem5 = ddlpid5.Items.FindByValue(ddlpid2.SelectedValue);
ddlpid5.Items.Remove(removeItem5);
}
else if (ddlpid2.SelectedItem.Text.Equals("Police ID"))
{
FillDropdown(ddlpid1);
FillDropdown(ddlpid2);
FillDropdown(ddlpid3);
FillDropdown(ddlpid4);
FillDropdown(ddlpid5);
ddlpid1.SelectedValue = (String)Session["pid1"];
ddlpid1_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid3.SelectedValue = (String)Session["pid3"];
ddlpid3_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid4.SelectedValue = (String)Session["pid4"];
ddlpid4_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid5.SelectedValue = (String)Session["pid5"];
ddlpid5_SelectedIndexChanged(this, EventArgs.Empty);
}
}
protected void ddlpid3_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlpid3.SelectedIndex > 0)
{
Session["pid3"] = ddlpid3.SelectedValue;
ListItem removeItem1 = ddlpid1.Items.FindByValue(ddlpid3.SelectedValue);
ddlpid1.Items.Remove(removeItem1);
ListItem removeItem2 = ddlpid2.Items.FindByValue(ddlpid3.SelectedValue);
ddlpid2.Items.Remove(removeItem2);
ListItem removeItem4 = ddlpid4.Items.FindByValue(ddlpid3.SelectedValue);
ddlpid4.Items.Remove(removeItem4);
ListItem removeItem5 = ddlpid5.Items.FindByValue(ddlpid3.SelectedValue);
ddlpid5.Items.Remove(removeItem5);
}
else if (ddlpid3.SelectedItem.Text.Equals("Police ID"))
{
FillDropdown(ddlpid1);
FillDropdown(ddlpid2);
FillDropdown(ddlpid3);
FillDropdown(ddlpid4);
FillDropdown(ddlpid5);
ddlpid1.SelectedValue = (String)Session["pid1"];
ddlpid1_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid2.SelectedValue = (String)Session["pid2"];
ddlpid2_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid4.SelectedValue = (String)Session["pid4"];
ddlpid4_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid5.SelectedValue = (String)Session["pid5"];
ddlpid5_SelectedIndexChanged(this, EventArgs.Empty);
}
}
protected void ddlpid4_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlpid4.SelectedIndex > 0)
{
Session["pid4"] = ddlpid4.SelectedValue;
ListItem removeItem1 = ddlpid1.Items.FindByValue(ddlpid4.SelectedValue);
ddlpid1.Items.Remove(removeItem1);
ListItem removeItem2 = ddlpid2.Items.FindByValue(ddlpid4.SelectedValue);
ddlpid2.Items.Remove(removeItem2);
ListItem removeItem3 = ddlpid3.Items.FindByValue(ddlpid4.SelectedValue);
ddlpid3.Items.Remove(removeItem3);
ListItem removeItem5 = ddlpid5.Items.FindByValue(ddlpid4.SelectedValue);
ddlpid5.Items.Remove(removeItem5);
}
else if (ddlpid4.SelectedItem.Text.Equals("Police ID"))
{
FillDropdown(ddlpid1);
FillDropdown(ddlpid2);
FillDropdown(ddlpid3);
FillDropdown(ddlpid4);
FillDropdown(ddlpid5);
ddlpid1.SelectedValue = (String)Session["pid1"];
ddlpid1_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid2.SelectedValue = (String)Session["pid2"];
ddlpid2_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid3.SelectedValue = (String)Session["pid3"];
ddlpid3_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid5.SelectedValue = (String)Session["pid5"];
ddlpid5_SelectedIndexChanged(this, EventArgs.Empty);
}
}
protected void ddlpid5_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlpid5.SelectedIndex > 0)
{
Session["pid5"] = ddlpid5.SelectedValue;
ListItem removeItem1 = ddlpid1.Items.FindByValue(ddlpid5.SelectedValue);
ddlpid1.Items.Remove(removeItem1);
ListItem removeItem2 = ddlpid2.Items.FindByValue(ddlpid5.SelectedValue);
ddlpid2.Items.Remove(removeItem2);
ListItem removeItem3 = ddlpid3.Items.FindByValue(ddlpid5.SelectedValue);
ddlpid3.Items.Remove(removeItem3);
ListItem removeItem4 = ddlpid4.Items.FindByValue(ddlpid5.SelectedValue);
ddlpid4.Items.Remove(removeItem4);
}
else if (ddlpid5.SelectedItem.Text.Equals("Police ID"))
{
FillDropdown(ddlpid1);
FillDropdown(ddlpid2);
FillDropdown(ddlpid3);
FillDropdown(ddlpid4);
FillDropdown(ddlpid5);
ddlpid1.SelectedValue = (String)Session["pid1"];
ddlpid1_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid2.SelectedValue = (String)Session["pid2"];
ddlpid2_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid3.SelectedValue = (String)Session["pid3"];
ddlpid3_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid4.SelectedValue = (String)Session["pid4"];
ddlpid4_SelectedIndexChanged(this, EventArgs.Empty);
}
}
First of all, I would set the AutoPostBack property for dropdowns to true in my markup:
<asp:DropDownList ID="memberID1" AutoPostBack="true" runat="server" Visible="false" OnSelectedIndexChanged="ddlpid1_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="memberID2" AutoPostBack="true" runat="server" Visible="false" OnSelectedIndexChanged="ddlpid2_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="memberID3" AutoPostBack="true" runat="server" Visible="false" OnSelectedIndexChanged="ddlpid3_SelectedIndexChanged" >
</asp:DropDownList>
Update: We can store selected values in view state and retrieve after repopulating the dropdownlists like below:
public partial class WebForm2 : System.Web.UI.Page
{
bool bFlag = true;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillddlLocations();
}
}
//Properties to store selected value in ViewState
protected string MemberID1Selection
{
get
{
if (ViewState["MemberID1Selection"] != null)
return ViewState["MemberID1Selection"].ToString();
return "";
}
set { ViewState["MemberID1Selection"] = value; }
}
protected string MemberID2Selection
{
get
{
if (ViewState["MemberID2Selection"] != null)
return ViewState["MemberID2Selection"].ToString();
return "";
}
set { ViewState["MemberID2Selection"] = value; }
}
protected string MemberID3Selection
{
get
{
if (ViewState["MemberID3Selection"] != null)
return ViewState["MemberID3Selection"].ToString();
return "";
}
set { ViewState["MemberID3Selection"] = value; }
}
protected void FillddlLocations()
{
FillDropdown(memberID1);
FillDropdown(memberID2);
FillDropdown(memberID3);
memberID1.Visible = true;
memberID2.Visible = true;
memberID3.Visible = true;
}
protected void FillDropdown(DropDownList ddl)
{
using (var connAdd = new SqlConnection("Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI"))
{
connAdd.Open();
var sql = "Select policeid from PoliceAccount where status ='available' and handle ='offcase' and postedto='" + ddllocation.SelectedValue + "'";
using (var cmdAdd = new SqlDataAdapter(sql, connAdd))
{
DataSet ds2 = new DataSet();
cmdAdd.Fill(ds2);
ddl.Items.Clear();
ddl.DataSource = ds2;
ddl.DataTextField = "memberID";
ddl.DataValueField = "memberID";
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("Please select a Member ID", ""));
ddl.SelectedIndex = 0;
}
}
}
protected void IndexChanged(DropDownList ddlChanged, DropDownList ddlToFilter1, DropDownList ddlToFilter2)
{
string removeValue1 = ddlChanged == memberID1 ? MemberID1Selection : (ddlChanged == memberID2 ? MemberID2Selection : MemberID3Selection);
string selValue2 = ddlChanged == memberID1 ? MemberID2Selection : (ddlChanged == memberID2 ? MemberID1Selection : MemberID1Selection);
string selValue3 = ddlChanged == memberID1 ? MemberID3Selection : (ddlChanged == memberID2 ? MemberID3Selection : MemberID2Selection);
bFlag = false;//Prevent fireing the code again while changing the index
if (removeValue1 != "")
{
ListItem item1 = ddlToFilter1.Items.FindByValue(removeValue1);
ddlToFilter1.Items.Remove(item1);
ListItem item2 = ddlToFilter2.Items.FindByValue(removeValue1);
ddlToFilter2.Items.Remove(item2);
}
if (selValue3 != "")
{
ListItem item3 = ddlToFilter1.Items.FindByValue(selValue3);
ddlToFilter1.Items.Remove(item3);
}
if (selValue2 != "")
{
ListItem item4 = ddlToFilter2.Items.FindByValue(selValue2);
ddlToFilter2.Items.Remove(item4);
}
bFlag = false;
ddlToFilter1.SelectedIndex = ddlToFilter1.Items.IndexOf(ddlToFilter1.Items.FindByValue(selValue2));
ddlToFilter2.SelectedIndex = ddlToFilter2.Items.IndexOf(ddlToFilter2.Items.FindByValue(selValue3));
}
protected void ddlpid1_SelectedIndexChanged(object sender, EventArgs e)
{
MemberID1Selection = memberID1.SelectedValue;
if (bFlag)
{
FillDropdown(memberID2);
FillDropdown(memberID3);
IndexChanged(memberID1, memberID2, memberID3);
}
}
protected void ddlpid2_SelectedIndexChanged(object sender, EventArgs e)
{
MemberID2Selection = memberID2.SelectedValue;
if (bFlag)
{
FillDropdown(memberID1);
FillDropdown(memberID3);
IndexChanged(memberID2, memberID1, memberID3);
}
}
protected void ddlpid3_SelectedIndexChanged(object sender, EventArgs e)
{
MemberID3Selection = memberID3.SelectedValue;
if (bFlag)
{
FillDropdown(memberID1);
FillDropdown(memberID2);
IndexChanged(memberID3, memberID1, memberID2);
}
}
}
I have tested the code and it is working for me. Hope it helps!
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.
I am developing an online exam system project using ASP.NET (C#) & SQL Sever.
This is my code. I have a problem in implementing code for next & previous button. Please suggest me the answer. Thank you.
public partial class Default : Page
{
int count;
string ans;
int[] a=new int[5];
int t;
int ctr;
SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"].ToString());
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand();
DataSet ds = new DataSet();
DateTime myDate;
DataTable dt = new DataTable();
DataRow dr;
public void Show()
{
Session["Answered"] = dt;
View v = this.View1;
Label l = default(Label);
l = (Label)v.FindControl("Label1");
l.Text = dt.Rows[ctr]["Serial"] + ".";
l = (Label)v.FindControl("Label2");
l.Text = dt.Rows[ctr]["question"].ToString();
RadioButtonList r = default(RadioButtonList);
r = (RadioButtonList)v.FindControl("RadioButtonList1");
r.Items.Clear();
r.Items.Add(dt.Rows[ctr]["choice1"].ToString());
r.Items.Add(dt.Rows[ctr]["choice2"].ToString());
r.Items.Add(dt.Rows[ctr]["choice3"].ToString());
r.Items.Add(dt.Rows[ctr]["choice4"].ToString());
r.SelectedIndex = Convert.ToInt32(dt.Rows[ctr]["selected"]);
Session["ctr"] = ctr;
}
protected void Timer1_Tick(object sender, System.EventArgs e)
{
DateTime mydate2 = DateTime.Now;
DateTime mydate3 = default(DateTime);
try
{
mydate3 = Convert.ToDateTime((myDate - mydate2).ToString());
this.Label5.Text = "Time Left: " + mydate3.ToShortTimeString();
}
catch (Exception ex)
{
this.Label5.Text = "Error Setting up the Timer. Contact Admin";
}
if (mydate3.ToShortTimeString() == "00:00:00")
{
int marks = 0;
Session["Answered"] = dt;
Response.Redirect("default3.aspx?marks=" + marks);
}
}
protected void Page_Load(object sender, System.EventArgs e)
{
DateTime myDate = new DateTime();
myDate =Convert.ToDateTime(Request.Cookies["start"].Value);
if (!IsPostBack) {
this.MultiView1.ActiveViewIndex = 0;
conn.Open();
cmd.Connection = conn;
Random arbit = new Random();
for (int i = 0; i <= a.GetUpperBound(0); i++) {
t = arbit.Next(1, 10);
if (Array.IndexOf(a, t) == -1) {
a[i] = t;
} else {
goto X;
}
}
for (int i = 0; i <= 4; i++)
{
cmd.CommandText = "select * from test where Serial=" + a[i];
da.SelectCommand = cmd;
da.Fill(ds, "test");
}
conn.Close();
dt = new DataTable("Answered");
dt.Columns.Add("Serial", typeof(int));
dt.Columns.Add("question", typeof(string));
dt.Columns.Add("choice1", typeof(string));
dt.Columns.Add("choice2", typeof(string));
dt.Columns.Add("choice3", typeof(string));
dt.Columns.Add("choice4", typeof(string));
dt.Columns.Add("correct", typeof(string));
dt.Columns.Add("selected", typeof(int));
DataRow r = null;
foreach (DataRow r_loopVariable in ds.Tables["test"].Rows) {
r = r_loopVariable;
dr = dt.NewRow();
dr["Serial"] = dt.Rows.Count + 1;
dr["question"] = r["question"];
dr["choice1"] = r["choice1"];
dr["choice2"] = r["choice2"];
dr["choice3"] = r["choice3"];
dr["choice4"] = r["choice4"];
dr["correct"] = r["correct"];
dr["selected"] = -1;
dt.Rows.Add(dr);
}
Session["Answered"] = dt;
Show();
}
}
protected void btnNext_Click(object sender, EventArgs e)
{
Session["ctr"] = ctr;
Session["Answered"] = dt;
Session["ctr"] = ctr;
ctr += 1;
Show();
if (ctr == 4)
{
this.btnNext.Enabled = false;
}
this.btnPrev.Enabled = true;
}
protected void btnPrev_Click(object sender, EventArgs e)
{
Session["ctr"] = ctr;
Session["Answered"] = dt;
ctr = ctr - 1;
if (ctr == 0)
{
this.btnPrev.Enabled = false;
}
Session["ctr"] = ctr;
this.btnNext.Enabled = true;
Show();
}
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
RadioButtonList1.SelectedIndexChanged += new EventHandler(RadioButtonList1_SelectedIndexChanged);
Session["Answered"] = dt;
}
protected void btnShowMarks_Click(object sender, EventArgs e)
{
int marks = 0;
Session["Answered"] = dt;
Response.Redirect("default3.aspx?marks=" + marks);
Session["marks"] = dt;
int []b=new int[6];
foreach (int c in b)
{
RadioButtonList1.SelectedIndex.ToString();
}
}
}
I would suggest you to use the Wizard control.
Here are some examples:
http://msdn.microsoft.com/en-us/magazine/cc163894.aspx
http://www.codeproject.com/KB/aspnet/Wizard_Control.aspx
Since you seem to develop a wizard-like form did you consider using the Wizard control.
You can Fetch random data from DB and store it in a dataset. Then there you can get questions in usual manner. Then you can fetch questions using a variable which will store the question number to get previous and next questions. If user clicks on Previous then variable - 1 also +1 if next