Friday, February 24, 2012

Calendar Control and Database Connection

Hi,
I m trying to implement a calendar, where you can select certain dates and view list of events for that day. The list is generated from database. I found a script on the web that is quite similar to what i want to achieve. I tried to run this script, however I get an exeption saying:

An error has occurred while establishing a connection to the server. ... error: 40 - Could not open a connection to SQL Server)

This is the code:
SqlConnection mycn;
SqlDataAdapter myda;
DataSet ds = new DataSet();
DataSet dsSelDate;
String strConn;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
strConn = "Data Source=localhost;Initial Catalog=pubs";

mycn = new SqlConnection(strConn);
myda = new SqlDataAdapter("Select * FROM EventsTable", mycn);
myda.Fill(ds, "Table"); //This where I get the exeption
}

protected void CalendarDRender(object sender, System.Web.UI.WebControls.DayRenderEventArgs e)
{
// If the month is CurrentMonth
if (!e.Day.IsOtherMonth)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
if ((dr["EventDate"].ToString() != DBNull.Value.ToString()))
{
DateTime dtEvent = (DateTime)dr["EventDate"];
if (dtEvent.Equals(e.Day.Date))
{
e.Cell.BackColor = System.Drawing.Color.PaleVioletRed;
}
}
}
}
//If the month is not CurrentMonth then hide the Dates
else
{
e.Cell.Text = "";
}
}

private void Calendar1_SelectionChanged(object sender, System.EventArgs e)
{
myda = new SqlDataAdapter("Select * from EventsTable where EventDate='" +
Calendar1.SelectedDate.ToString() + "'", mycn);
dsSelDate = new DataSet();
myda.Fill(dsSelDate, "AllTables");
if (dsSelDate.Tables[0].Rows.Count == 0)
{
DataGrid1.Visible = false;
}
else
{
DataGrid1.Visible = true;
DataGrid1.DataSource = dsSelDate;
DataGrid1.DataBind();
}
}


Can some one tell me what is wrong with the code.
Thank You

WATCH THIS SPACE

I resolve the issue by correcting the connection string within the strCon.

WATCH THIS SPACE

No comments:

Post a Comment