How to populate the date present in the database table to Calender asp.net? - asp.net

My table in the database has the following columns id , eventstart , eventend , eventname
I am trying to bind the event name plus the event start date in the cell of the calender on the date which it is occurring
However i am not able to do so
Following is my code snippet
protected void myCal_DayRender1(object sender, DayRenderEventArgs e)
{
DataSet ds = new DataSet();
SqlDataAdapter cmd = new SqlDataAdapter("Select * FROM event", con);
cmd.Fill(ds, "Table");
if (!e.Day.IsOtherMonth)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
if ((dr["eventstart"].ToString() != DBNull.Value.ToString()))
{
DateTime dtEvent = (DateTime)dr["eventstart"];
if (dtEvent.Equals(e.Day.Date))
{
Label lbl = new Label();
lbl.BorderColor = System.Drawing.Color.Black;
lbl.BorderStyle = BorderStyle.Double;
lbl.Width = 100;
lbl.Height = 100;
lbl.BackColor = System.Drawing.Color.BlanchedAlmond;
lbl.Text = TextBoxName.Text + "" + TextBoxStart.Text + "" + TextBoxEnd.Text;
e.Cell.Controls.Add(lbl);
}
}
}
}
else
{
}
}
Please help someone

Ok, once again from the start. Now I think I got it. Your problem is probably caused by comparing date with time to date. To get only date without time You can use dt.Date as You can see below. You can consider loading all data on page load because of performance reasons.
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
//get data
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand =
new SqlCommand("select * from event", connection);
adapter.Fill(ds);
}
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
//mark dates in calendar
foreach (DataRow dr in ds.Tables[0].Rows)
{
DateTime dt = (DateTime)dr.Field<DateTime?>("eventstart");
if (e.Day.Date == dt.Date)
{
e.Cell.BackColor = System.Drawing.Color.Yellow;
//add event lable to day
Label lbl = new Label();
lbl.BorderColor = System.Drawing.Color.Black;
lbl.BorderStyle = BorderStyle.Double;
lbl.BackColor = System.Drawing.Color.BlanchedAlmond;
lbl.Text = "Event text";
e.Cell.Controls.Add(lbl);
}
}
}

Related

duplicate items in dropdownlist on an edit page

I have a page to edit user profile.On page load,the data loads on to the page for the given userid.The problem is that the dropdownlists have a duplicate item which is selected.as shown below :
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//btnReset.Visible = false;
BindDisabilityDropDown();
BindGenderDropDown();
BindStateDropDown();
ExtractUserData();
}
}
protected void BindGenderDropDown()
{
string CS = ConfigurationManager.ConnectionStrings["ss"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from tblGenders", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ddlGender.DataSource = ds;
ddlGender.DataTextField = "GenderName";
ddlGender.DataValueField = "GenderId";
ddlGender.DataBind();
}
ddlGender.Items.Insert(0, new ListItem("---Select---", "0"));
ddlGender.SelectedIndex = 0;
}
private void ExtractUserData()
{
string CS = ConfigurationManager.ConnectionStrings["ss"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tblAllUsers where UserId='PL00012'", con);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string path = rdr["ProfilePicPath"].ToString();
hfImagePath.Value = Path.GetFileName(path);
lblUserId.Text = rdr["UserId"].ToString();
txtFName.Text = rdr["FirstName"].ToString();
txtLName.Text = rdr["LastName"].ToString();
txtEmailAddress.Text = rdr["EmailAdd"].ToString();
txtContactNumber.Text = rdr["MobileNo"].ToString();
txtdob.Value = rdr["DOB"].ToString();
txtStreetAddress.Text = rdr["StreetAddress"].ToString();
txtZipCode.Text = rdr["ZipCode"].ToString();
ddlGender.SelectedItem.Text = rdr["Gender"].ToString();
ddlDisabled.SelectedItem.Text = rdr["Disabled"].ToString();
ddlState.SelectedItem.Text = rdr["State"].ToString();
ddlCity.SelectedItem.Text = rdr["City"].ToString();
}
}
What i am guessing is,the dropdownlist is loaded by BindGenderDropDown() and then the SelectedItem is added once again by ExtractData().So how can i just avoid the unwanted addition?
You can do the following while selecting DropdownList SelectedItem in ExtractUserData() method:
ddlGender.SelectedIndex = ddlGender.Items.IndexOf(ddlGender.Items.FindByText(rdr["Gender"].ToString()));
Your code ddlGender.SelectedItem.Text = rdr["Gender"].ToString(); is displaying ---Select--- with rdr["Gender"].ToString(). This code doesn't change the Items but only chooses the item.
it may help you.
if (ddlGender.Items.Contains(ddlGender.Items.FindByText(rdr["Gender"].ToString())))
{
ddlGender.Items.FindByText(rdr["Gender"].ToString()).Selected = true;
}
In your case, ddlGender.SelectedItem.Text = rdr["Gender"].ToString(); is changing text of selected index and so it is changing --Select-- to Your Selected Value.
and for selection of Item in Dropdown, I'd suggest to use below code.
ddlGender.SelectedValue = rdr["GenderId"].ToString();

how to get total of all column if GridView Paging is set as “True”?

this code display total of column in each page of grid view footer I want to display total of all columns in all pages footer
if (e.Row.RowType == DataControlRowType.DataRow)
{
string deb = ((Label)e.Row.FindControl("debit")).Text;
string cred = ((Label)e.Row.FindControl("credit")).Text;
decimal totalvalue = Convert.ToDecimal(deb) - Convert.ToDecimal(cred);
amount += totalvalue;
Label lbl = (Label)e.Row.FindControl("lblTotal");
lbl.Text = amount.ToString();
Label lblDebAmount = (Label)e.Row.FindControl("debit");
Label lblCredamount = (Label)e.Row.FindControl("credit");
float debtotal = (float)Decimal.Parse(lblDebAmount.Text);
float credtotal = (float)Decimal.Parse(lblCredamount.Text);
totalPriced += debtotal;
totalPricec += credtotal;
}
if (e.Row.RowType == DataControlRowType.Footer)
{
Label totallblCAmount = (Label)e.Row.FindControl("totallblDebAmount");
Label totallblCredAmount = (Label)e.Row.FindControl("totallblCredAmount");
totallblCAmount.Text = totalPriced.ToString("###,###.000");
totallblCredAmount.Text = totalPricec.ToString("###,###.000");
}
}
Why do it when the row is data bound? Why not do it when you originally bind the data?
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
DataTable dt = Database.GetData();
GridView1.DataSource = dt;
GridView1.DataBind();
//calculate here by manually adding up the debit/credit column from dt
//or do a separate database call that calculates the sum, ex: select sum(debits), sum(credits) from general_ledger
}
}
It makes sense to let the database do the math calculation for you. You wouldn't need to write your own custom calculation code. Just let the database's sum function handle it.
Here's a little more detail.
//Executes a SqlCommand and returns a DataTable
public class GetDataTable(SqlCommand command)
{
var dt = new DataTable();
using (var connection = new SqlConnection("connectionstring"))
{
command.Connection = connection;
connection.Open();
dt.Load(command.ExecuteReader());
}
return dt;
}
//Executes a SqlCommand and returns a scalar of type T
public static T GetScalar<T>(SqlCommand command)
{
using (var connection = new SqlConnection ("connectionstring"))
{
command.Connection = connection;
connection.Open();
var result = command.ExecuteScalar();
if (result is T)
{
return (T)result;
}
else
{
return (T)Convert.ChangeType(result, typeof(T));
}
}
}
//Load the data into the GridView, then get the credit amount and put the value in a label.
//You'll need to adjust the queries to match your schema
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
var tableCommand = new SqlCommand("select columns from table");
GridView1.DataSource = GetDataTable(tableCommand);
GridView1.DataBind();
var creditCommand = new SqlCommand("select sum(stat_amount) from tablename where stat_flag='c'");
var credits = GetScalar<decimal>(creditCommand);
Label1.Text = credits;
}
}

Dynamically adding Table rows

I am trying to add values in table rows on button click. It's working on database but not working on web page. It override on last row on page.
How can I generate new row on every button click.
here is my button click code--
protected void Page_Load(object sender, EventArgs e)
{
tblAdd.Visible = false;
Label1.Visible = false;
//Label2.Visible = false;
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
CheckBox cb1 = new CheckBox();
I = Hidden1.Value;
I += 1;
cb1.ID = "cb1" + I;
TableRow Table1Row = new TableRow();
Table1Row.ID = "Table1Row" + I;
TableCell RCell1 = new TableCell();
RCell1.Controls.Add(cb1);
TableCell RCell2 = new TableCell();
RCell2.Text = txtName.Text;
tblLanguagesRow.Cells.Add(RCell1);
tblLanguagesRow.Cells.Add(RCell2);
tblLanguages.Rows.Add(tblLanguagesRow);
Hidden1.Value = I;
btnAdd.Visible = true;
btnDelete.Visible = true;
Label2.Visible = true;
Label2.Text = "Successfully Added";
add();
}
txtName.Text = "";
}
public int add()
{
string strcon = ConfigurationManager.ConnectionStrings["Dbconnection"].ConnectionString;
SqlConnection sqlConnection = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("hrm_AddLanguages", sqlConnection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#Name", SqlDbType.VarChar).Value = txtName.Text;
command.Parameters.Add("#CreatedOn", SqlDbType.DateTime).Value = DateTime.Now;
command.Parameters.Add("#UpdatedOn", SqlDbType.DateTime).Value = DateTime.Now;
command.Parameters.Add("#CreatedBy", SqlDbType.BigInt).Value = 1;
command.Parameters.Add("#UpdatedBy", SqlDbType.BigInt).Value = 1;
command.Parameters.Add("#IsDeleted", SqlDbType.Bit).Value = 0;
sqlConnection.Open();
return command.ExecuteNonQuery();
}
Please Help me.
If possible try to do this using Grid view. It is better to use grid view instead of table.
Check out below link. It will help you to find your solution.
DataTable in ASP.Net Session

Gridview does not show SQL Server database records

I'm designing a web system for my fyp.
I use SqlDependency to get table change info from cache.
I used SqlDataAdapter, dataSet and gridview, but it doesn't show any result on screen.
Can you tell me where the problem is in my code?
protected void refresh_Click(object sender, EventArgs e)
{
if (Cache["shipOrders"] == null)
{
gvshipOrders.DataSource = Cache["shipOrders"];
gvshipOrders.DataBind();
lblOrderNotification.Text = "last order recived at " + DateTime.Now.ToString();
}
else
{
string xconnectionString = ConfigurationManager.ConnectionStrings["LGDB"].ToString();
SqlConnection sqlCon = new SqlConnection(xconnectionString);
SqlDataAdapter da = new SqlDataAdapter("viewOrders", sqlCon);
DataSet ds = new DataSet();
da.Fill(ds);
SqlCacheDependency XsqlcacheDependecy = new SqlCacheDependency("secaloTest1", "customerShipOrder");
//caching shipOrders table data
/*
Cache.Insert("shipOrders", ds, null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
another overloaded method is used */
Cache.Insert("shipOrders", ds, XsqlcacheDependecy);
gvshipOrders.DataSource = ds;
gvshipOrders.DataBind();
lblOrderNotification.Text = "orders retrived from database at " + DateTime.Now.ToString();
}
}
I've found the problem,
public partial class OrderProccessing : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["email"] == null)
{
Response.Redirect("Default.aspx");
}
else
{
string value = Session["email"].ToString();
Classes.AddAddress addcuid = new Classes.AddAddress(value);
txtstaffname.Text = addcuid.addStaffName().ToString();
txtstaffID.Text = addcuid.fetchStaffID().ToString();
}
}
protected void refresh_Click(object sender, EventArgs e)
{
if (Cache["shipOrders"] != null)
{
myGrid.DataSource = Cache["ShipOrders"];
myGrid.DataBind();
lblOrderNotification.Text = "last order recived at " + DateTime.Now.ToString();
}
else
{
string xconnectionString = ConfigurationManager.ConnectionStrings["LGDB"].ToString();
SqlConnection sqlCon = new SqlConnection(xconnectionString);
SqlDataAdapter da = new SqlDataAdapter("viewOrders", sqlCon);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
da.Fill(ds);
SqlCacheDependency XsqlcacheDependecy = new SqlCacheDependency("secaloTest1", "customerShipOrder");
//caching shipOrders table data
/*
Cache.Insert("shipOrders", ds, null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
another overloaded method is used */
Cache.Insert("shipOrders", ds, XsqlcacheDependecy);
myGrid.DataSource = ds;
myGrid.DataBind();
lblOrderNotification.Text = "orders retrived from database at " + DateTime.Now.ToString();
}
}
}

Dynamically added checkboxs are not working in asp.net using c#?

i am adding multiple checkboxes in my asp.net page by doing this:
public static CheckBox[] chck;
on pageload:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
con.Open();
SqlCommand cmd = new SqlCommand("select count(CompanyName) from Stock_Company");
cmd.Connection = con;
comno = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
chck = new CheckBox[comno];
}
}
now i have a function which is generating the checkboxes :
public void generatecheckbox1()
{
con.Open();
SqlCommand cmd = new SqlCommand("select CompanyName from Stock_Company");
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
con.Close();
for (int i = 0; i < dt.Rows.Count; i++)
{
chck[i] = new CheckBox();
chck[i].ID = "chck" + Convert.ToString(i);
chck[i].Text = dt.Rows[i]["CompanyName"].ToString();
pnlcom1.Controls.Add(chck[i]);
pnlcom1.Controls.Add(new LiteralControl("<br />"));
}
}
and i am calling this on a combobox event:
protected void ddluserwebser_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddluserwebser.SelectedItem.Text == "Custom")
{
generatecheckbox1();
}
}
as far as this all are working fine ... but in a button click i want to get the select checkbox's text which i am not getting
i made a function :
public string getbsecompany()
{
string companyname = "";
string bsetricker = "";
con.Open();
SqlCommand cmd = new SqlCommand("select CompanyName from Stock_Company");
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
con.Close();
for (int i = 0; i < dt.Rows.Count; i++)
{
if (chck[i].Checked == true) **THE PROBLEM IS HERE**
{
companyname = chck[i].Text;
con.Open();
SqlCommand cmdd = new SqlCommand("select BSETickerCode from Stock_Company where CompanyName='" + companyname + "'");
cmdd.Connection = con;
bsetricker += bsetricker + "+" + cmdd.ExecuteScalar();
con.Close();
}
}
return bsetricker;
}
and i am calling it here:
protected void btnusersave_Click(object sender, EventArgs e)
{
string bsetricker = "";
bsetricker = getbsecompany();
}
the problem is i am not getting the checked box's text. when i am checking if (chck[i].Checked == true) i am gettin false and all checkboxes are checked.
What should i do now?
any help
The dynamic controls should added to page in On_Init() for each time if you want it display in page.
Else there's nothing you can get.
Plus, better not use a static value to contains checkBox List, it will cause problem when multi user access same page. You can save them in session or try this.Form.FindControls()

Resources