I have an SQL DB which is filled with users (id,First_Name,Surname,Email_Account,etc..).
Im Searching the DataBase based on Name and i show links , If that link is clicked then it redirects you to the users page.
My problem is when i try to pass the session variables, so when the link gets clicked then pageload is loading from the Session variables.
So when i have multiple search results , with the way i do it the last result session variables pass.
Here's the code! :)
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace DisplayingImages
{
public partial class WebForm7 : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=MPAPASYMEON;Server=mpapasymeon;Database=LOGIN;Initial Catalog=LOGIN; User ID=nikolaossts; Password=aaa;Connect Timeout=240");
string PID2;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
DataTable PassRecord = new DataTable();
String str = "select First_Name,Email_Account,Surname,id from ID where (First_Name like '%'+ #search +'%' ) OR (Surname like '%'+ #search +'%') OR (Email_Account like '%'+ #search +'%')";
SqlCommand Srch = new SqlCommand(str, con);
Srch.Parameters.Add("#search", SqlDbType.NVarChar).Value = TextBox1.Text;
if (TextBox1.Text != "")
{
con.Open();
Srch.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = Srch;
DataTable dt = new DataTable();
DataSet ds = new DataSet();
da.Fill(dt);
DataTable Results = new DataTable;
PID =(int)( Session["id"]);
int SaveTheFirst = PID;
foreach (DataRow dr in dt.Rows)
{
PID2 = dr["id"].ToString();
if (PID.ToString() != PID2 )
{
var field = "<a href='" + Page.ResolveUrl("~/PageView.aspx?Email=" + dr["id"].ToString()) + "'>" + (dr["First_Name"] + "").ToString() + "</a>";
Session["SurnameView"] = dr["Surname"];
string check1 = dr["Surname"].ToString();
Session["idView"] = dr["id"];
string check2 = dr["id"].ToString();
Session["EmailView"] = dr["Email_Account"];
string check3 = dr["Email_Account"].ToString();
Response.Write(field);
HttpContext context = HttpContext.Current;
Response.Write("<br/>");
}
}
con.Close();
}
else
{
string display = " Not Valid Search Criteria!";
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + display + "');", true);
}
}
public string SN { get; set; }
public string PS { get; set; }
public string EM { get; set; }
public int PID { get; set; }
}
}
Why not put an identifier to each session? Like for instance, the ID of your user or something else that you can map to? That way you will be able to associate each session, with a user - after creating the sessions. Otherwise, if you don't use a unique identifier that does not match your business logic, you would not be able to associate the session...
foreach (DataRow dr in dt.Rows)
{
PID2 = dr["id"].ToString();
if (PID.ToString() != PID2 )
{
var field = "<a href='" + Page.ResolveUrl("~/PageView.aspx?Email=" + dr["id"].ToString()) + "'>" + (dr["First_Name"] + "").ToString() + "</a>";
Session["SurnameView_" + PID2 ] = dr["Surname"];
string check1 = dr["Surname"].ToString();
Session["idView_" + PID2] = dr["id"];
string check2 = dr["id"].ToString();
Session["EmailView_" + PID2] = dr["Email_Account"];
string check3 = dr["Email_Account"].ToString();
Response.Write(field);
HttpContext context = HttpContext.Current;
Response.Write("<br/>");
}
}
Have a look at these links to get a better idea of how to create unique sessions per user
Creating unique sessions per user on Webforms ASP.net
how safe is it to use session variables - asp.net / c#
One way to save it in the session
int counter = 0;
foreach (DataRow dr in dt.Rows)
{
PID2 = dr["id"].ToString();
if (PID.ToString() != PID2 )
{
counter+=1;
//do stuff
Session["Email_" + counter] = dr["Surname"];
}
}
But in this case you should add the counter to the url parameters.
var field = "<a href='" + Page.ResolveUrl("~/PageView.aspx?Email=" + dr["id"].ToString()) + "&counter=" + counter "'>" + (dr["First_Name"] + "").ToString() + "</a>";
In this case when you open the page you will know which session parameter is needed.
The other way is just to write all of your values in the Url and take them after that.
I suggest using a HiddenField to store the data in which you want to pass. Session is not really reliable for multiple instances
Related
I am trying to create a chart that when, at the push of a button displays a chart that shows the user the number of times a record has appeared in the dataset/table that it is linked to. Please bare in mind that I have little experience with using Charts in Visual Studios/C#.
Currently I am getting this error: Error
This is all the code I have so far:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace RRAS
{
public partial class formRRAS : Form
{
public OleDbConnection DataConnection = new OleDbConnection();
public formRRAS()
{
InitializeComponent();
}
private void formRRAS_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'database1DataSet.tblReject_test' table. You can move, or remove it, as needed.
this.tblReject_testTableAdapter.Fill(this.database1DataSet.tblReject_test);
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnSearch_Click(object sender, EventArgs e)
{
//This creates the String Publisher which grabs the information from the combo box on the form.
//Select and Dataconnection are also defined here.
string Select = "SELECT * FROM tblReject_test";
string DataConnection;
string Department = txtDepartment.Text;
string Start_Date = txtStart.Text;
string End_Date = txtEnd.Text;
string Anatomy = txtAnatomy.Text;
string RFR = cmbRFR.Text;
string Comment = txtComment.Text;
//Select defines what should be loaded on to the dataset.
if (Department != "")
{
Select = Select + " WHERE department_id =" + "'" + Department + "'";
if (Anatomy != "")
{
Select = Select + "AND body_part_examined =" + "'" + Anatomy + "'";
if (Start_Date != "")
{
Select = Select + " AND study_date =" + "'" + Start_Date + "'";
if (End_Date != "")
{
Select = Select + " AND study_date =" + "'" + End_Date + "'";
if (RFR != "")
{
Select = Select + " AND reject_category =" + "'" + RFR + "'";
if(Comment != "")
{
Select = Select + " AND reject_comment =" + "'" + Comment + "'";
}
}
}
}
}
}
else
{
Select = "SELECT * FROM tblReject_test";
}
//DataConnection connects to the database.
string connectiontring= "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring);
//The DataAdapter is the code that ensures both the data in the Select and DataConnection strings match.
OleDbDataAdapter rdDataAdapter = new OleDbDataAdapter(Select, DataConnection);
try
{
//It then clears the datagridview and loads the data that has been selected from the DataAdapter.
database1DataSet.tblReject_test.Clear();
rdDataAdapter.Fill(this.database1DataSet.tblReject_test);
}
catch (OleDbException exc)
{
System.Windows.Forms.MessageBox.Show(exc.Message);
}
}
private void btnLoadChart_Click(object sender, EventArgs e)
{
try
{
int count = database1DataSet.Tables["tblReject_test"].Rows.Count;
DataConnection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = DataConnection;
string query = "SELECT * FROM tblReject_test";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
charRejections.Series["RFR"].Points.AddXY(reader["reject_category"].ToString(), reader[count].ToString());
}
DataConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
}
}
Your code wouldn't compile as you are assigning a string to DataConnection (instance of OleDbConnection).
The correct usage should be as following.
string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring));
Also, your code doesn't close Database connection in case of exception.
It would be recommended to use the code as shown below. This is taken from MSDN
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
try
{
connection.Open();
Console.WriteLine("DataSource: {0} \nDatabase: {1}",
connection.DataSource, connection.Database);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}
I am trying to pass a protected DataRow[] msgArray; from code-behind to the .net page.
msgArray contains rows from a DB table that I selected, when I do Response.Write(msgArray[0]["comment"]) it outputs correctly what I have stored in the comment column in my DB.
The problem is that I cannot do the same in my .net page when I load the page where I do this:
<asp:Panel ID="commentSection" runat="server">
<%= msgArray[0]["comment"] %>
</asp:Panel>
I get a Object reference not set to an instance of an object.
What am I doing wrong ?
This is my code-behind(.cs) :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using MySql.Data.MySqlClient;
namespace Groups
{
public partial class Group : System.Web.UI.Page
{
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
MySql.Data.MySqlClient.MySqlDataReader reader;
String queryStr;
String gname;
String gtype;
String uname;
DataTable group = new DataTable();
DataTable msg = new DataTable();
protected DataRow[] msgArray;
protected void Page_Load(object sender, EventArgs e)
{
String id = Request.QueryString["id"];
if (id != null)
{
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["GroupsConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "SELECT g.*, (SELECT COUNT(id) FROM app_groups.users_groups_leg ugl WHERE ugl.id_group = g.id) as member_count FROM app_groups.groups g WHERE g.id = " + id;
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
group.Load(reader = cmd.ExecuteReader());
var groupArray = group.AsEnumerable().ToArray();
reader.Close();
int member_count = 0;
int.TryParse(groupArray[0]["member_count"].ToString(), out member_count);
Panel grInfo = new Panel();
grInfo.Controls.Add(new LiteralControl("<br/><div class='panel panel-primary'><div class='panel-heading'><h2>" + groupArray[0]["group_name"] + "</h2></div><div class='panel-body'><span>Categorie: <span class='title'>" + groupArray[0]["group_type"] + "</span></span><br/><span class='membrii'>" + (member_count == 1 ? member_count + " membru" : member_count + " membri") + "</span><br/><span>Fondat pe: " + ConvertUnixTimeStamp(groupArray[0]["founded"].ToString()) + "</span><br/></div></div>"));
groupInfo.Controls.Add(grInfo);
conn.Close();
showComments();
}
}
public static DateTime? ConvertUnixTimeStamp(string unixTimeStamp)
{
return new DateTime(1970, 1, 1).AddSeconds(Convert.ToDouble(unixTimeStamp) + 3600*2);
}
public DataRow[] showComments()
{
String id = Request.QueryString["id"];
if (id != null)
{
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["GroupsConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "SELECT gc.* FROM app_groups.group_comments gc WHERE gc.id_group = " + id;
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
msg.Load(reader = cmd.ExecuteReader());
msgArray = msg.AsEnumerable().ToArray();
reader.Close();
Response.Write(msgArray[0]["comment"]);
/*Panel grComments = new Panel();
grComments.Controls.Add(new LiteralControl(""));
groupInfo.Controls.Add(grComments);*/
}
return msgArray;
}
}
}
Create a new class dataAccess.cs
using System;
using System.Data;
namespace Groups
{
public class dataAccess
{
public List<string> GetComments()
{
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["GroupsConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
try
{
MySql.Data.MySqlClient.MySqlDataReader reader;
DataTable msg = new DataTable();
conn.Open();
List<string> comments = new List<string>();
queryStr = "SELECT gc.* FROM app_groups.group_comments gc WHERE gc.id_group = " + id;
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
msg.Load(reader = cmd.ExecuteReader());
foreach(DataRow dr in msg.Rows)
{
comments.Add(dr["comment"]);
}
reader.Close();
return comments;
}
catch (Exception ex)
{
//throw ex;
}
}
}
}
In the ASPX page
<asp:Panel ID="commentSection" runat="server">
<%
var data = Groups.dataAccess.GetComments();
foreach(string c in data)
{
Response.Write("<p>" + c + "</p>");
}
%>
</asp:Panel>
According to ASP.NET Page Life cycle, your method showComments() will be called after the <%= msgArray[0]["comment"] %> part. Hence it won't be available there.
Best way is to have a control like Label in your .aspx page and update the text property from showComments() method.
I have created an app linked to a local database. It works well, but the only problem is that after I press the insert button, data is inserted in db, but it is not showed in the GridView, only after I close and reopen the application. How can I make it show the data right after I press the button which inserts the values? Thanks !
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlServerCe;
using System.IO;
namespace Gradinita
{
public partial class Grupa : Form
{
string nume = "";
List<Label> labels = new List<Label>();
public Grupa(string nume)
{
InitializeComponent();
this.nume = nume;
}
private void Grupa_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'grupeDataSet8.copii' table. You can move, or remove it, as needed.
this.copiiTableAdapter2.Fill(this.grupeDataSet8.copii);
// TODO: This line of code loads data into the 'grupeDataSet7.copii' table. You can move, or remove it, as needed.
this.copiiTableAdapter1.Fill(this.grupeDataSet7.copii);
// TODO: This line of code loads data into the 'grupeDataSet3.copii' table. You can move, or remove it, as needed.
this.copiiTableAdapter.Fill(this.grupeDataSet3.copii);
var connString = (#"Data Source=" + System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) + #"\Grupe.sdf");
using (var conn = new SqlCeConnection(connString))
{
try
{
conn.Open();
var query = "SELECT * FROM grupe WHERE Nume='" + nume + "'";
var command = new SqlCeCommand(query, conn);
var dataAdapter = new SqlCeDataAdapter(command);
var dataTable = new DataTable();
dataAdapter.Fill(dataTable);
label1.Text = dataTable.Rows[0][0].ToString();
label2.Text = dataTable.Rows[0][1].ToString();
label3.Text = dataTable.Rows[0][2].ToString();
label4.Text = dataTable.Rows[0][3].ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
private void button1_Click(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
label5.Text = ("1");
}
if (checkBox2.Checked)
{
label5.Text = ("0");
}
textBox1.Text = (Convert.ToInt32(textBox5.Text) - Convert.ToInt32(textBox6.Text)).ToString();
var connString = (#"Data Source=" + Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + #"\Grupe.sdf");
using (var conn = new SqlCeConnection(connString))
{
try
{
conn.Open();
var query = "INSERT INTO copii(prezenta, Nume, Prenume, Program, Taxa, Achitat, Diferenta) VALUES('" + label5.Text + "', '" + textBox2.Text.Trim() + "', '" + textBox3.Text.Trim() + "', '" + textBox4.Text.Trim() + "', '" + textBox5.Text.Trim() + "', '"+ textBox6.Text.Trim()+"', '"+ textBox1.Text.Trim() +"');";
MessageBox.Show(query);
var command = new SqlCeCommand(query, conn);
command.ExecuteNonQuery();
dataGridView1.Refresh(); //not working obviously
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
You need to re-query the data and rebind the datatable.
Something like:
dataGridView1.DataSource = SomeDataTableSource;
dataGridView1.DataBind();
I managed to bypass this by re-adding the grid to the control. First, you copy the grid in a variable, then you remove it from the parent control, and then you add the variable to the controls of that control.
var grid = dataGridView1.Parent.Controls["dataGridView1"];
var ctr = dataGridView1.Parent;
ctr.Controls.Remove(dataGridView1);
ctr.Controls.Add(grid);
It's not tested and I might have mistaken some names cause i don't have a VS installed here, but you get the idea. Not the most elegant solution, but it worked for me. You can also try dataGridView1.Refresh() - which it didn't work for me.
I have a method (AddRowToSQLTable()) that is passed a row, it then creates a row array containing that row and then passes it to DataTable.update().
This works fine. The SQL Server is updated and the next time I run (debug) the program the new data is present.
Another method (AddStock()) uses a similar structure but does not work.
The difference being that I am passing a data table in Update() not a Row[] however no exception is thrown just nothing is updated/added on the server.
Can someone please explain what exactly is going on and why these differ? I would like to know this even if the solution is to use a different structure to achieve what I want so I know for the future and have a better understanding.
To Note:
I have tested to ensure the DataTable being passed contains records. The DataTable is of the same format as the target SQL Server table.
I have also tried SqlBulkCopy and encounter the same problem.
Many thanks!
private DataTable StockAdditions;
public void PrepareStockQuantitiesForAdding()
{
if (StockAdditions != null)
{
StockAdditions.Clear();
}
StockAdditions = StockQuantitiesTable.Clone();
int Count = 0;
DataRow RowToAdd = StockQuantitiesTable.NewRow();
DataView AreaIDs = new DataView(AreaTable);
DataView Conditions = new DataView(ConditionsTable);
int AreaID;
string ConditionCode;
foreach (DataRow Row in SessionSKUScanned.Rows)
{
if (Row["Serial Number"].ToString() == "")
{
Conditions.RowFilter = "([Name] = '" + Row["Condition"] + "')";
ConditionCode = Conditions[0][2].ToString();
AreaIDs.RowFilter = "([StorageAreaName] = '" + Row["Area"] + "')";
AreaID = Convert.ToInt32(AreaIDs[0][0]);
DataView StockQuantities = new DataView(StockQuantitiesTable);
StockQuantities.RowFilter = "([QuantityID] = '" + AreaID + "-" + Row["SKU"] + "-" + ConditionCode + "')";
if (StockQuantities.Count > 0)
{
StockQuantities[0][3] = Convert.ToInt32(StockQuantities[0][3]) + 1;
RowToAdd["QuantityID"] = AreaID + "-" + Row["SKU"] + "-" + ConditionCode;
RowToAdd["SKU"] = Row["SKU"];
RowToAdd["AreaID"] = AreaID;
RowToAdd["Quantity"] = StockQuantities[0][3] = Convert.ToInt32(StockQuantities[0][3]) + 1;
RowToAdd["Condition"] = Row["Condition"];
}
else
{
RowToAdd["QuantityID"] = AreaID + "-" + Row["SKU"] + "-" + ConditionCode;
RowToAdd["SKU"] = Row["SKU"];
RowToAdd["AreaID"] = AreaID;
RowToAdd["Quantity"] = 1;
RowToAdd["Condition"] = Row["Condition"];
}
Count++;
}
else
{
RowToAdd["QuantityID"] = Row["Serial Number"];
RowToAdd["SKU"] = Row["SKU"];
AreaIDs.RowFilter = "([StorageAreaName] = '" + Row["Area"] + "')";
RowToAdd["AreaID"] = Convert.ToInt32(AreaIDs[0][0]);
RowToAdd["Quantity"] = 1;
RowToAdd["Condition"] = Row["Condition"];
Count++;
}
StockQuantitiesTable.ImportRow(RowToAdd);
MessageBox.Show(RowToAdd[0].ToString());
StockAdditions.ImportRow(RowToAdd);
}
}
private void AddRowToSQLTable(DataRow Row, string SQLTableName)
{
DataRow[] Rows = new DataRow[1];
Rows[0] = Row;
SqlConnection SQLConn = new SqlConnection(ConfigurationManager.ConnectionStrings["eCommStock.Properties.Settings.Demo_SiteConnectionString"].ConnectionString);
SQLConn.Open();
SqlDataAdapter daUpdateTable = new SqlDataAdapter("Select * From " + SQLTableName, SQLConn);
SqlCommandBuilder SQLcmdBuilder = new SqlCommandBuilder(daUpdateTable);
daUpdateTable.Update(Rows);
SQLConn.Close();
}
public void AddStock()
{
SqlConnection SQLConn = new SqlConnection(ConfigurationManager.ConnectionStrings["eCommStock.Properties.Settings.Demo_SiteConnectionString"].ConnectionString);
SQLConn.Open();
SqlDataAdapter daUpdateTable = new SqlDataAdapter("Select * From StockQuantities", SQLConn);
SqlCommandBuilder SQLcmdBuilder = new SqlCommandBuilder(daUpdateTable);
daUpdateTable.Update(StockAdditions);
SQLConn.Close();
}
It doesn't work because RowToAdd.RowState is Detached. I don't like it, but the following is a quick and dirty solution, before importing the row to StockAdditions, make sure the row is in Added state, later you can "detach" the row again.
StockQuantitiesTable.Rows.Add(RowToAdd);
StockAdditions.ImportRow(RowToAdd);
StockQuantitiesTable.Rows.Remove(RowToAdd);
I have an sql select script that will execute and shows that there is data being selected when it is run. The problem I am having is trying to get that data to show in my calendar control. I wanted to change the calender by what department the user was from that logged in. Right now there is nothing showing and it will not show any data unless I hard code a department in it.
I am working with c# asp.net.
here is what I am doing to try and get the data
private DataSet GetData()
{
var CurrUser = "a73 ";
var UsrDepartment = "60 ";
Account.Login uusr = new Account.Login();
CurrUser = uusr.User.Identity.Name.ToString().ToUpper();
ConnectionStringSettingsCollection cssc = ConfigurationManager.ConnectionStrings;
var sql = "select (substring(status, 1,1)) AS stat1, lastname, firstname, ldate, edate,depdivid, requestid from TIME.employee E inner join TIME.request T on E.EMPID = T.empid where E.depdivid = #UsrDepartment ";
using (iDB2Connection conn = new iDB2Connection(GetConnectionString()))
{
conn.Open();
using (iDB2Command cmd = new iDB2Command(sql, conn))
{
cmd.DeriveParameters();
using (iDB2DataAdapter da = new iDB2DataAdapter(cmd))
{
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
}
}
I fill the calendar with this :
DataSet ds = GetData();
foreach (DataRow row in ds.Tables[0].Rows)
{
//need to fill from first to last date
string scheduledDate = Convert.ToDateTime(row["ldate"]).ToShortDateString();
string endDate = Convert.ToDateTime(row["edate"]).ToShortDateString();
e.Cell.Width = 120;
e.Cell.Height = 100;
Int32 start = 0;
Int32 end = 0;
start = string.CompareOrdinal(scheduledDate, s);
end = string.CompareOrdinal(endDate, s);
if ((start <= 0) & (end >= 0) & (!e.Day.IsWeekend))
{
HyperLink lb = new HyperLink();
lb.Text = link + (Int64)row["requestid"] + "' >" + row["lastname"] + "</a>" as String + "(" + row["stat1"] + ")" as String + "<br />";
//code to change color of button
if (scheduledDate == endDate)
{
lb.CssClass = "changecolor";
}
e.Cell.Controls.Add(lb);
}
}
This way will show no links in my calendar, but if I make the department have a value(which is not what I wanted) it will show the links.
I think you need a line like this
cmd.Parameters["#UsrDepartment"].Value = myDept