Multiple dropdowns from different databases on a single view in asp.net mvc4 - asp.net

The following code i have used in web form and i want to convert it into asp.net mvc4 with four buttons and their events and grid.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MasterFiles
{
public partial class WebForm1 : System.Web.UI.Page
{
//This is the connection string
public static String connstr = "Data Source=23.22.136.160;Initial Catalog=Medcare;Persist Security Info=True;User ID=sa;Password=dlink";
//This is common method to bind the drop downs
public static void FillDDList(ref DropDownList DropDownName, String Query)
{
using (SqlConnection con = new SqlConnection(connstr))
{
con.Open();
SqlDataReader dr;
try
{
//Check whether the Drop Down has existing items. If YES, empty it.
if (DropDownName.Items.Count > 0)
DropDownName.Items.Clear();
SqlCommand cmd = new SqlCommand(Query, con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
ListItem extLI = new ListItem();
extLI.Value = dr[0].ToString();
extLI.Text = dr[1].ToString();
DropDownName.Items.Add(extLI);
}
dr.Close();
con.Close();
}
catch (Exception ex)
{
con.Close();
//RunCustomScript("alert('" + ex.Message.ToString() + "')", callingPageObjectName);
}
}
}
//This is the method to bind the grid.
public static bool FillGridBySqlString(ref System.Web.UI.WebControls.GridView GVW, string strSQL)
{
SqlConnection conn = new SqlConnection();
System.Data.SqlClient.SqlCommand SqlComm1 = new System.Data.SqlClient.SqlCommand();
DataSet ds = new DataSet();
DataTable dt_Kit = new DataTable();
//DataTable dt_Items = new DataTable();
SqlDataAdapter ListAdapter = new SqlDataAdapter();
conn.ConnectionString = connstr;
SqlCommand dataSelectCommand = new SqlCommand();
dataSelectCommand.CommandType = CommandType.Text;
dataSelectCommand.CommandText = strSQL;
dataSelectCommand.CommandType = System.Data.CommandType.Text;
dataSelectCommand.Connection = conn;
ListAdapter.SelectCommand = dataSelectCommand;
ListAdapter.Fill(dt_Kit);
dt_Kit.TableName = "Kit";
ds.Tables.Add(dt_Kit);
GVW.DataSource = ds;
GVW.DataMember = "Kit";
GVW.DataBind();
try
{
dt_Kit.Clear();
ds.Tables.Remove(dt_Kit);
ds.Clear();
}
catch
{
}
return true;
}
//This is the method to execute the sql command.
public static void execNonQuerySQL(string sql)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = connstr;
DataSet ds = new DataSet();
SqlCommand dataSelectCommand = new SqlCommand();
try
{
dataSelectCommand.CommandType = CommandType.Text;
dataSelectCommand.CommandText = sql;
dataSelectCommand.Connection = conn;
conn.Open();
dataSelectCommand.ExecuteNonQuery();
}
catch { }
conn.Close();
dataSelectCommand.Dispose();
}
public static void execNonQuerySSP(string StoredProcName, Object[,] parmarr)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = connstr;
DataSet ds = new DataSet();
SqlCommand dataSelectCommand = new SqlCommand();
try
{
dataSelectCommand.CommandType = CommandType.StoredProcedure;
dataSelectCommand.CommandText = StoredProcName;
dataSelectCommand.Connection = conn;
conn.Open();
for (int i = 0; i < parmarr.Length / 2; )
{
dataSelectCommand.Parameters.AddWithValue("#" + parmarr[i, 0], parmarr[i, 1]);
if (parmarr[i++, 0] == null) break;
}
dataSelectCommand.ExecuteNonQuery();
}
catch { }
conn.Close();
dataSelectCommand.Dispose();
}
string sqlstr = "select " +
" (Select '(BCO_ID:'+Convert(varchar(5),B.MCM_APP_ID) +') -'+C.BCO_CODE+':'+C.BCO_DESCRIPTION BCO_TEXT From MasterCodesMap B,Medcare.dbo.Billing_Code C Where B.MCM_APP_ACRO = 'VMGR' AND B.MCM_VM_ID = A.MCM_VM_ID AND C.BCO_ID=B.MCM_APP_ID ) [Base Data in VM/Medcare], " +
" (Select '(BCO_ID:'+Convert(varchar(5),B.MCM_APP_ID) +') -'+C.BCO_CODE+':'+C.BCO_DESCRIPTION BCO_TEXT From MasterCodesMap B,Pils.dbo.Billing_Code C Where B.MCM_APP_ACRO = 'PILS' AND B.MCM_VM_ID = A.MCM_VM_ID AND C.BCO_ID=B.MCM_APP_ID ) [Mapped Data in PILS System], " +
" (Select '(BCO_ID:'+Convert(varchar(5),B.MCM_APP_ID) +') -'+C.BCO_CODE+':'+C.BCO_DESCRIPTION BCO_TEXT From MasterCodesMap B,Alg.dbo.Billing_Code C Where B.MCM_APP_ACRO = 'ALG' AND B.MCM_VM_ID = A.MCM_VM_ID AND C.BCO_ID=B.MCM_APP_ID ) [Mapped Data in ALG System], " +
" (Select '(BCO_ID:'+Convert(varchar(5),B.MCM_APP_ID) +') -'+C.BCO_CODE+':'+C.BCO_DESCRIPTION BCO_TEXT From MasterCodesMap B,Boise1.dbo.Billing_Code C Where B.MCM_APP_ACRO = 'USI' AND B.MCM_VM_ID = A.MCM_VM_ID AND C.BCO_ID=B.MCM_APP_ID ) [Mapped Data in USI System] " +
" from MasterCodesMap A where MCM_APP_ACRO = 'VMGR' " +
" Order by 2 ";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillDDList(ref DropDownList1, "SELECT -1,'No Virtual Manager Match' UNION select BCO_ID,BCO_DESCRIPTION + ' =>'+ BCO_CODE BCO_TEXT from Medcare.dbo.Billing_Code Order by 1");
FillDDList(ref DropDownList2, "SELECT -1,'No Virtual Manager Match' UNION select BCO_ID,BCO_DESCRIPTION + ' =>'+ BCO_CODE BCO_TEXT from PILS.dbo.Billing_Code Order by 1");
FillDDList(ref DropDownList3, "SELECT -1,'No Virtual Manager Match' UNION select BCO_ID,BCO_DESCRIPTION + ' =>'+ BCO_CODE BCO_TEXT from ALG.dbo.Billing_Code Order by 1");
FillDDList(ref DropDownList4, "SELECT -1,'No Virtual Manager Match' UNION select BCO_ID,BCO_DESCRIPTION + ' =>'+ BCO_CODE BCO_TEXT from Boise1.dbo.Billing_Code Order by 1");
FillGridBySqlString(ref GridView1, sqlstr);
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Set the hand mouse cursor for the selected row.
e.Row.Attributes.Add("OnMouseOver", "this.style.cursor = 'hand';");
//////// The seelctButton exists for ensuring the selection functionality
//////// and bind it with the appropriate event hanlder.
//////LinkButton selectButton = new LinkButton()
//////{
////// CommandName = "Select",
////// Text = e.Row.Cells[0].Text
//////};
//////selectButton.Font.Underline = false;
//////selectButton.ForeColor = System.Drawing.Color.Beige;
//////e.Row.Cells[3].Controls.Add(selectButton);
////////e.Row.Attributes["OnClick"] =
//////// Page.ClientScript.GetPostBackClientHyperlink(selectButton, "");
//////e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if(DropDownList1.SelectedIndex != 0)
{
Object[,] parmarr = {
{ "TABLE_ACRO", "BLCD"},
{ "Orig_MCM_ID", -1 },
{ "App_ACRO", "VMGR" },
{ "VMID", DropDownList1.SelectedValue},
{ "APP_ID", DropDownList1.SelectedValue},
};
execNonQuerySSP("crtMasterCodesMap",parmarr);
}
if (DropDownList2.SelectedIndex != 0)
{
Object[,] parmarr = {
{ "TABLE_ACRO", "BLCD"},
{ "Orig_MCM_ID", -1 },
{ "App_ACRO", "PILS" },
{ "VMID", DropDownList1.SelectedValue},
{ "APP_ID", DropDownList2.SelectedValue},
};
execNonQuerySSP("crtMasterCodesMap", parmarr);
}
if (DropDownList3.SelectedIndex != 0)
{
Object[,] parmarr = {
{ "TABLE_ACRO", "BLCD"},
{ "Orig_MCM_ID", -1 },
{ "App_ACRO", "ALG" },
{ "VMID", DropDownList1.SelectedValue},
{ "APP_ID", DropDownList3.SelectedValue},
};
execNonQuerySSP("crtMasterCodesMap", parmarr);
}
if (DropDownList4.SelectedIndex != 0)
{
Object[,] parmarr = {
{ "TABLE_ACRO", "BLCD"},
{ "Orig_MCM_ID", -1 },
{ "App_ACRO", "USI" },
{ "VMID", DropDownList1.SelectedValue},
{ "APP_ID", DropDownList4.SelectedValue},
};
execNonQuerySSP("crtMasterCodesMap", parmarr);
}
FillGridBySqlString(ref GridView1, sqlstr);
}
protected void Button2_Click(object sender, EventArgs e)
{
execNonQuerySQL("delete MasterCodesMap where MCM_VM_ID = " + DropDownList1.SelectedValue);
FillGridBySqlString(ref GridView1, sqlstr);
}
protected void Button3_Click(object sender, EventArgs e)
{
Object[,] parmarr = {
{ "iVM_ID", DropDownList1.SelectedValue},
{ "iTABLE_ACRO", "BLCD"}
};
execNonQuerySSP("synchVMMasterData", parmarr);
FillGridBySqlString(ref GridView1, sqlstr);
}
protected void Button4_Click(object sender, EventArgs e)
{
FillGridBySqlString(ref GridView1, sqlstr);
}
}
}

you can pass your data for dropdownlist by ViewBag:
ViewBag.ProfileId = new SelectList(db.UserProfiles, "Id", "Username");
and get in your view :
#Html.DropDownList("ProfileId", String.Empty)
or another example :
Controller
public ActionResult Index()
{
List<SelectListItem> obj1 = new List<SelectListItem>();
obj1.Add(new SelectListItem { Text = "Text1", Value = "1" });
obj1.Add(new SelectListItem { Text = "Text2", Value = "2" });
obj1.Add(new SelectListItem { Text = "Text3", Value = "3" });
List<SelectListItem> obj2 = new List<SelectListItem>();
obj2.Add(new SelectListItem { Text = "Text1", Value = "1" });
obj2.Add(new SelectListItem { Text = "Text2", Value = "2" });
obj2.Add(new SelectListItem { Text = "Text3", Value = "3" });
ViewBag.State1 = obj1;
ViewBag.State2 = obj2;
return View();
}
View
#Html.DropDownList(“State1”)
#Html.DropDownList(“State2”)
but in my opinion better way is using ViewModel for this issue .

Related

"Cannot implicitly convert type 'Lab06.Attendance' to 'System.Collections.Generic.List<Lab06.Attendance>" How to solve this error

AssignmentAttendance.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services.Description;
namespace Lab06 {
public partial class AssignmentAttendance : System.Web.UI.Page
{
Attendance aAttendance = new Attendance();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bind();
}
}
protected void bind()
{
List<Attendance> attendancelist = new List<Attendance>();
attendancelist = aAttendance.getAttendanceAll();
GridView1.DataSource = attendancelist;
GridView1.DataBind();
}
protected void Retrieve_Attendance_Click(object sender, EventArgs e)
{
string attributename = tb_classcode.ToString();
List<Attendance> attendanceList = new List<Attendance>();
attendanceList = aAttendance.getAttendance(attributename);
GridView1.DataSource = attendanceList;
GridView1.DataBind();
}
/* protected void edit_attendance(object sender, GridViewEditEventArgs e)
{
}*/
}
}
AssignmentContentUploadClass.cs
public class Attendance {
string _connStr =ConfigurationManager.ConnectionStrings["HealthDBContext"].ConnectionString;
private string _ClassCode = null;
private string _Teacher_ID = "";
private string _TeachingSessions = "";
private string _Remarks = "";
public Attendance()
{
}
// Constructor that take in all data required to build a Product object
public Attendance(string ClassCode, string Teacher_ID, string TeachingSessions, string Remarks)
{
_ClassCode = ClassCode;
_Teacher_ID = Teacher_ID;
_TeachingSessions = TeachingSessions;
_Remarks = Remarks;
}
public string ClassCode
{
get { return _ClassCode; }
set { _ClassCode = value; }
}
public string Teacher_ID
{
get { return _Teacher_ID; }
set { _Teacher_ID = value; }
}
public string TeachingSessions
{
get { return _TeachingSessions; }
set { _TeachingSessions = value; }
}
public string Remarks
{
get { return _Remarks; }
set { _Remarks = value; }
}
public int createAttendance()
{
int result = 0;
string queryStr = "INSERT INTO Attendance(ClassCode, Teacher_ID, TeachingSessions, Remarks)"
+ " values (#ClassCode, #Teacher_ID, #TeachingSessions, #Remarks)";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#ClassCode", this.ClassCode);
cmd.Parameters.AddWithValue("#Teacher_ID", this.Teacher_ID);
cmd.Parameters.AddWithValue("#TeachingSessions", this.TeachingSessions);
cmd.Parameters.AddWithValue("#Remarks", this.Remarks);
conn.Open();
result += cmd.ExecuteNonQuery(); // Returns no. of rows affected. Must be > 0
conn.Close();
return result;
}//end Insert
public Attendance getAttendance(string ClassCode)
{
Attendance attendanceDetail = null;
string Teacher_ID, TeachingSessions, Remarks;
string queryStr = "Select * From Attendance Where ClassCode = #ClassCode";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#ClassCode", ClassCode);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Teacher_ID = dr["Teacher_ID"].ToString();
TeachingSessions = dr["TeachingSessions"].ToString();
Remarks = dr["Remarks"].ToString();
attendanceDetail = new Attendance(ClassCode, Teacher_ID, TeachingSessions, Remarks);
}
else
{
attendanceDetail = null;
}
conn.Close();
dr.Close();
dr.Dispose();
return attendanceDetail;
}
public List<Attendance> getAttendanceAll()
{
List<Attendance> attendancelist = new List<Attendance>();
string ClassCode, Teacher_ID, TeachingSessions, Remarks;
string queryStr = "SELECT * FROM Attendance Order By ClassCode";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
ClassCode = dr["ClassCode"].ToString();
Teacher_ID = dr["Teacher_ID"].ToString();
TeachingSessions = dr["TeachingSessions"].ToString();
Remarks = dr["Remarks"].ToString();
Attendance a = new Attendance(ClassCode, Teacher_ID, TeachingSessions, Remarks);
attendancelist.Add(a);
}
conn.Close();
dr.Close();
dr.Dispose();
return attendancelist;
}
}
I am not sure of the error and thus I am not able to provide much
I am trying use the getAttendance(ClassCode) function to retrieve the data based off my input of my classcode in the textbox of my AssignmentAttendance.aspx.
I am thinking of using the getAttendance function in my AssignmentAttendance.aspx file by passing in the data of my classcode entry from the textbox to retrieve the details of the Attendance based off classcode.
However, I am not too sure how that works and might need some help
My database has:
ClassCode
Teacher_ID
TeachingSessions
Remarks
If anything is missing or I did not make things clear do let me know
-Edit-
I am getting an error from my AssignmentAttendance.aspx.cs file
attendanceList = aAttendance.getAttendance(attributename);

How can I get link to include mailto: in aspx file?

<tr>
<td style="border-bottom: 1px #c7c6c6 solid;">
<strong>
<asp:Label ID="Label6" runat="server" Text="Email:"></asp:Label>
</strong> </td>
<td style="border-bottom: 1px #c7c6c6 solid;">
<asp:HyperLink ID="EmailLink" runat="server"> <asp:Label ID="lblEmail" runat="server"></asp:Label></asp:HyperLink>
</td>
</tr>
Code Behind:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.DirectoryServices;
using System.Data.SqlClient;
using System.Data;
using System.Text;
using System.Data.OracleClient;
using System.Configuration; //added
public partial class ADdata : System.Web.UI.Page
{
SqlConnection Conn;
DirectoryEntry dirEntry;
protected void Page_Load(object sender, EventArgs e)
{
lblStatus.Text = "";
string connOra =
ConfigurationManager.ConnectionStrings["UNHBannerPRODConnString"].ConnectionString;
//Conn = new SqlConnection(matrixDBConnectString);
//string ADUser = ConfigurationManager.AppSettings["ADUser"];
//string ADPassword = ConfigurationManager.AppSettings["ADPassword"];
//dirEntry = new DirectoryEntry(ADPath, ADUser, ADPassword, AuthenticationTypes.Secure);
string ADPath = ConfigurationManager.AppSettings["ADPath"];
dirEntry = new DirectoryEntry(ADPath);
FillFixed_DeptPhoneNo();
if (!Page.IsPostBack)
{
//-- fill up important phone numbers
//FillFixed_DeptPhoneNo();
string strSQL = "Select distinct(deptname) from UNH_ADDepartments order by deptname";
OracleConnection con = new OracleConnection(connOra);
OracleCommand cmd = new OracleCommand(strSQL, con);
cmd.Connection.Open();
OracleDataReader drfilldd = cmd.ExecuteReader();
//SqlCommand cmdfilldd = new SqlCommand("Select distinct(deptname) from UNH_ADDepartments order by deptname", Conn);
//Conn.Open();
//SqlDataReader drfilldd = cmdfilldd.ExecuteReader();
Dept.DataSource = drfilldd;
Dept.DataTextField = "deptname";
Dept.DataValueField = "deptname";
Dept.DataBind();
Dept.Items.Insert(0, new ListItem("-- Select Department -- ", "-1"));
drfilldd.Dispose();
cmd.Dispose();
con.Close();
con.Dispose();
//Conn.Close();
}
}
public void FillFixed_DeptPhoneNo()
{
//Add important phone numbers into panel pPhoneNo
}
public void FillGrid(string filter)
{
DirectorySearcher search = new DirectorySearcher(dirEntry);
search.Filter = filter;
search.PropertiesToLoad.Add("name");
search.PropertiesToLoad.Add("mail");
search.PropertiesToLoad.Add("department");
search.PropertiesToLoad.Add("title");
SearchResultCollection searchResultCollection = search.FindAll(); //Here FindAll()!
DataTable dataTableResults = new DataTable();
dataTableResults.Columns.Add("NAME");
dataTableResults.Columns.Add("Mail");
dataTableResults.Columns.Add("DEPARTMENT");
dataTableResults.Columns.Add("TITLE");
foreach (SearchResult sr in searchResultCollection)
{
DataRow dataRow = dataTableResults.NewRow();
DirectoryEntry de = sr.GetDirectoryEntry();
dataRow["name"] = de.Properties["Name"].Value;
dataRow["mail"] = de.Properties["mail"].Value;
dataRow["department"] = de.Properties["department"].Value;
dataRow["title"] = de.Properties["title"].Value;
string d = dataRow["Department"].ToString();
if (d == " " || d == "")
{
dataRow["Department"] = null;
}
dataTableResults.Rows.Add(dataRow);
de.Close();
}
if (dataTableResults.Rows.Count > 1)
{
lblFullName.Text = "";
lblDepartment.Text = "";
lblTitle.Text = "";
lblExtension.Text = "";
lblPhone.Text = "";
lblOffice.Text = "";
lbluserPrincipalName.Text = "";
lblEmail.Text = "";
EmailLink.NavigateUrl = "";
lblFax.Text = "";
//Select only rows with non empty email and properly formed name.
//Sort dataTableResults by Department, Name before binding to GridView2.
DataView dataView = new DataView(dataTableResults);
dataView.RowFilter = #"Mail LIKE '%newhaven.edu'
AND Mail NOT LIKE '%0#newhaven.edu'
AND Mail NOT LIKE '%1#newhaven.edu'
AND Mail NOT LIKE '%2#newhaven.edu'
AND Mail NOT LIKE '%3#newhaven.edu'
AND Mail NOT LIKE '%4#newhaven.edu'
AND Mail NOT LIKE '%5#newhaven.edu'
AND Mail NOT LIKE '%6#newhaven.edu'
AND Mail NOT LIKE '%7#newhaven.edu'
AND Mail NOT LIKE '%8#newhaven.edu'
AND Mail NOT LIKE '%9#newhaven.edu'
AND Name NOT LIKE '%0'
AND Name NOT LIKE '%1'
AND Name NOT LIKE '%2'
AND Name NOT LIKE '%3'
AND Name NOT LIKE '%4'
AND Name NOT LIKE '%5'
AND Name NOT LIKE '%6'
AND Name NOT LIKE '%7'
AND Name NOT LIKE '%8'
AND Name NOT LIKE '%9'";
dataView.Sort = "Department ASC, Name ASC";
GridView2.DataSource = dataView; // = dataTableResults;
GridView2.DataBind();
Panel4.Visible = false;
GridView2.Visible = true;
}
else
{
Panel4.Visible = true;
GridView2.Visible = false;
}
} //FillGrid()
protected void btnSearch_Click(object sender, EventArgs e)
{
lblStatus.Text = "";
//btnSearch.Visible = false;
if (txtLastName.Text.Trim() == "" && txtName.Text.Trim() == "" && Dept.SelectedIndex == 0)
{
lblStatus.Text = "Please enter either Firstname or Lastname or Department to search.";
return;
}
try
{
string filter = "(&";
if (txtLastName.Text.Trim().Length > 0)
filter += "(sn=" + txtLastName.Text.Trim() + "*)";
if (txtName.Text.Trim().Length > 0)
filter += "(givenName=" + txtName.Text.Trim() + "*)";
if (Dept.SelectedIndex > 0)
filter += "(department=" + Dept.SelectedValue.Trim() + ")"; //department comes from ddl
filter += ")";
//Response.Write("filter=[" + filter + "]<br/>");
DirectorySearcher dirSearcher = new DirectorySearcher(dirEntry);
dirSearcher.Filter = filter;
SearchResult searchResult = dirSearcher.FindOne();
DirectoryEntry oneDirEntry = searchResult.GetDirectoryEntry();
string v = oneDirEntry.Properties["userAccountControl"].Value.ToString();
if (v == "66050")
{
lblStatus.Text = "This person is not enabled in the System.";
Panel4.Visible = false;
GridView2.Visible = false;
return;
}
UnpackDirectoryEntry(oneDirEntry);
FillGrid(filter);
}
catch (Exception ex)
{
//lblStatus.Text = (ex.Message == null ? "No Record found" : ex.Message);
lblStatus.Text = "No Record found" ; //updated 3/24/2017 AChen. The message is not meaningful to the user
GridView2.Visible = false;
Panel4.Visible = false;
}
} //btnSearch_Click()
public void UnpackDirectoryEntry(DirectoryEntry dirEnt)
{
string FirstName;
string LastName;
if (dirEnt.Properties["givenName"].Value == null)
{
FirstName = "";
}
else
{
FirstName = dirEnt.Properties["givenName"].Value.ToString();
}
if (dirEnt.Properties["sn"].Value == null)
{
LastName = "";
}
else
{
LastName = dirEnt.Properties["sn"].Value.ToString();
lblFullName.Text = FirstName + " " + LastName;
}
if (dirEnt.Properties["department"].Value == null)
{
lblDepartment.Text = "";
}
else
{
string Department = dirEnt.Properties["department"].Value.ToString();
lblDepartment.Text = Department;
}
if (dirEnt.Properties["title"].Value == null)
{
lblTitle.Text = "";
}
else
{
string Title = dirEnt.Properties["title"].Value.ToString();
lblTitle.Text = Title;
}
if (dirEnt.Properties["ipPhone"].Value == null)
{
lblExtension.Text = "";
}
else
{
string Phone = dirEnt.Properties["ipPhone"].Value.ToString();
lblExtension.Text = Phone;
}
if (dirEnt.Properties["physicalDeliveryOfficeName"].Value == null)
{
lblOffice.Text = "";
}
else
{
string Location = dirEnt.Properties["physicalDeliveryOfficeName"].Value.ToString();
lblOffice.Text = Location;
}
if (dirEnt.Properties["mail"].Value == null)
{
lblEmail.Text = "";
EmailLink.NavigateUrl = "";
}
else
{
string Mail = dirEnt.Properties["mail"].Value.ToString();
lblEmail.Text = Mail;
EmailLink.NavigateUrl = Mail;
}
if (dirEnt.Properties["cn"].Value == null)
{
lblFullName.Text = "";
}
else
{
string cn = dirEnt.Properties["cn"].Value.ToString();
lblFullName.Text = cn;
}
if (dirEnt.Properties["streetAddress"].Value == null)
{
lbluserPrincipalName.Text = "";
}
else
{
string building = dirEnt.Properties["streetAddress"].Value.ToString();
lbluserPrincipalName.Text = building;
}
if (dirEnt.Properties["telephoneNumber"].Value == null)
{
lblPhone.Text = "";
}
else
{
string Phone = dirEnt.Properties["telephoneNumber"].Value.ToString();
lblPhone.Text = Phone;
}
if (dirEnt.Properties["facsimiletelephonenumber"].Value == null)
{
lblFax.Text = "";
}
else
{
string fax = dirEnt.Properties["facsimiletelephonenumber"].Value.ToString();
lblFax.Text = fax;
}
}
protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
{
string EmailID = Convert.ToString(GridView2.SelectedRow.Cells[2].Text);
//DirectoryEntry dirEntry = new DirectoryEntry("LDAP://AD-NHLOCAL-03/OU=UNH Users, OU=UNH, dc= newhaven, dc= local", "Administrator", "AlphAomegA", AuthenticationTypes.Secure);
DirectorySearcher ds = new DirectorySearcher(dirEntry);
ds.Filter = "(mail= " + EmailID + ")"; //use email to identify a person in Active Directory!
SearchResult emailResults = ds.FindOne();
if (emailResults == null)
{
lblStatus.Text = "This entry cannot be selected because email=[" + EmailID + "].";
Panel4.Visible = false;
return;
}
DirectoryEntry employee = emailResults.GetDirectoryEntry();
UnpackDirectoryEntry(employee);
Panel4.Visible = true;
} //GridView2_SelectedIndexChanged()
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.color='#0153a3';this.style.cursor='hand';";
e.Row.Attributes["onmouseout"] = "this.style.color='Black';";
}
}
protected void txtName_TextChanged(object sender, EventArgs e)
{
GridView2.Visible = false;
Panel4.Visible = false;
//btnSearch.Visible = true;
}
protected void txtLastName_TextChanged(object sender, EventArgs e)
{
GridView2.Visible = false;
Panel4.Visible = false;
//btnSearch.Visible = true;
}
protected void Dept_SelectedIndexChanged(object sender, EventArgs e)
{
GridView2.Visible = false;
Panel4.Visible = false;
//btnSearch.Visible = true;
}
protected void btnCancel_Click(object sender, EventArgs e)
{
txtLastName.Text = "";
txtName.Text = "";
Dept.SelectedValue = "-1";
GridView2.Visible = false;
Panel4.Visible = false;
//btnSearch.Visible = false;
}
protected void GridView2_RowCreated(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[2].Visible = false;
}
}
I have a directory being displayed correctly, but would like to have the email clickable as a mailto: The code is being embedded on a page as an iFrame, so its adding the whole directory as a link for example the link appears, but is actually clicking to https://server.com/folder/email#something.com.
Looking at your code, you'd need to change this code:
EmailLink.NavigateUrl = Mail;
To be:
EmailLink.NavigateUrl = "mailto:" + Mail;

Grid View only updates when page refresh

In my application i have a grid view and a save task button. when i click save task my button , the Grid View doesn't refresh but when i click the refresh button of browser the grid refreshes and automatically add another task in the database. All i want is to refresh the grid when save task button is click and not add task when browser refresh button is clicked.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class Default2 : System.Web.UI.Page
{
static string startdate;
DataTable dt;
static string enddate;
static string EstDate;
string str = #"Data Source=ALLAH_IS_GREAT\sqlexpress; Initial Catalog = Task_Manager; Integrated Security = true";
protected void Page_Load(object sender, EventArgs e)
{//Page dosn't go back//
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetNoStore();
if (IsPostBack)
{
if (Session["auth"] != "ok" )
{
Response.Redirect("~/Login.aspx");
}
else if (Session["desg"] != "Scrum Master")
{
//Response.Redirect("~/errorpage.aspx");
addtaskbtnPannel.Visible = false;
}
}
else
{
GridView1.DataSource = dt;
GridView1.DataBind();
if (Session["auth"] != "ok")
{
Response.Redirect("~/Login.aspx");
}
else if (Session["desg"] != "Scrum Master")
{
// Response.Redirect("~/errorpage.aspx");
addtaskbtnPannel.Visible = false;
}
}
//decode url data in query string
labelID.Text = HttpUtility.UrlDecode(Request.QueryString["Id"]);
labelDur.Text = HttpUtility.UrlDecode(Request.QueryString["Duration"]);
labelStatus.Text = HttpUtility.UrlDecode(Request.QueryString["Status"]);
String pId = HttpUtility.UrlDecode(Request.QueryString["pID"]);
string query = "Select * from Tasks where S_ID=" + labelID.Text;
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand(query, con);
con.Open();
SqlDataReader sdr = null;
sdr = com.ExecuteReader();
dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Id"), new DataColumn("Description"), new DataColumn("Status"), new DataColumn("Sprint_ID"), new DataColumn("pID") });
while (sdr.Read())
{
dt.Rows.Add(sdr["T_ID"].ToString(), sdr["T_Description"].ToString(), sdr["T_Status"].ToString(), labelID.Text,pId);
}
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
if (!IsPostBack)
{
PanelTaskForm.Visible = false;
Panel1.Visible = false;
}
else if(IsPostBack){
PanelTaskForm.Visible = true;
Panel1.Visible = true;
}
}
protected void saveTask_Click(object sender, EventArgs e)
{
string str = #"Data Source=ALLAH_IS_GREAT\sqlexpress; Initial Catalog = Task_Manager; Integrated Security = true";
try
{
String query = "insert into Tasks (T_Description, T_Status,S_ID,StartDate,EstEndDate) values('" + TaskDesBox.Text + "', 'incomplete','" + labelID.Text + "' ,'" + startdate + "','" + EstDate + "');";
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand(query, con);
con.Open();
if (com.ExecuteNonQuery() == 1)
{
TaskStatus.Text = "Task Successfully Saved ";
GridView1.DataBind();
}
else
{
TaskStatus.Text = "Task not Saved";
}
}
catch (Exception ex)
{
Response.Write("reeor" + ex);
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void TaskDesBox_TextChanged(object sender, EventArgs e)
{
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
Calendar1.Visible = true;
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
startdate = Calendar1.SelectedDate.ToString("yyyy-MM-dd hh:mm:ss");
SDate.Text = startdate;
Calendar1.Visible = false;
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
Calendar2.Visible = true;
}
protected void Calendar2_SelectionChanged(object sender, EventArgs e)
{
EstDate = Calendar2.SelectedDate.ToString("yyyy-MM-dd hh:mm:ss");
EstDateBox.Text = EstDate;
Calendar2.Visible = false;
}
}
What you are doing on a post back is:
First show the results due to code in your Page_Load
Then perform event handlers, so if you pushed the Save button, the saveTask_Click will be performed, which adds a record to the database. You don't update your grid view datasource, but just call DataBind() afterwards which still binds the original DataSource.
Imo you shouldn't update your grid view on Page_Load. You should only show it initially on the GET (!IsPostBack).
And at the end of saveTask_Click you have to update your grid view again.
So move the code you need to show the grid view to a method you can call on other occasions:
protected void ShowGridView() {
String pId = HttpUtility.UrlDecode(Request.QueryString["pID"]);
string query = "Select * from Tasks where S_ID=" + labelID.Text;
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand(query, con);
con.Open();
SqlDataReader sdr = null;
sdr = com.ExecuteReader();
dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Id"), new DataColumn("Description"), new DataColumn("Status"), new DataColumn("Sprint_ID"), new DataColumn("pID") });
while (sdr.Read())
{
dt.Rows.Add(sdr["T_ID"].ToString(), sdr["T_Description"].ToString(), sdr["T_Status"].ToString(), labelID.Text,pId);
}
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
Then call it in your Page_Load on !IsPostBack
if (!IsPostBack)
{
ShowGridView();
PanelTaskForm.Visible = false;
Panel1.Visible = false;
}
else if(IsPostBack){
PanelTaskForm.Visible = true;
Panel1.Visible = true;
}
Then after adding the row in saveTask_Click you can call ShowGridView() to see the new result.
if (com.ExecuteNonQuery() == 1)
{
TaskStatus.Text = "Task Successfully Saved ";
//GridView1.DataBind();
ShowGridView();
}
else
{
TaskStatus.Text = "Task not Saved";
}

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();
}
}
}

how to return a datatable if a register number exists

I am trying to display a grid if the user entered register number exists in database, if the register number does not exists this means that I need to display one label also.i am a new one in asp.net,so please help me.
Here is my code below.
public DataTable madhrasaViewByRegNo(string viewByNo)
{
try
{
madhrasaInfo infomadhrasa = new madhrasaInfo();
object decobj = new object();
if (sqlcon.State == ConnectionState.Closed)
{
sqlcon.Open();
}
SqlCommand sqlcmd = new SqlCommand("madhrasaViewByRegNo", sqlcon);
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.Parameters.Add("#regNo", SqlDbType.VarChar).Value = viewByNo;
decobj = sqlcmd.ExecuteNonQuery();
if (decobj == null)
{
decStuId = decimal.Parse(decobj.ToString());
}
else
{
DataTable dtbClass = new DataTable();
SqlDataAdapter sqlda = new SqlDataAdapter("madhrasaViewByRegNo", sqlcon);
sqlda.SelectCommand.CommandType = CommandType.StoredProcedure;
sqlda.SelectCommand.Parameters.Add("#regNo", SqlDbType.VarChar).Value = viewByNo;
sqlda.Fill(dtbClass);
return dtbClass;
}
}
catch (Exception)
{
throw;
}
return null;
}
public void gridfillByNo()
{
madhrasaSp spMadhrasa = new madhrasaSp();
DataTable dtbl = new DataTable();
dtbl = spMadhrasa.madhrasaViewByRegNo(TextBox2.Text);
gvstuResult.DataSource = dtbl;
gvstuResult.DataBind();
}
public void regSearch()
{
madhrasaSp spmadhrasa = new madhrasaSp();
spmadhrasa.madhrasaViewByRegNo(TextBox2.Text);
if (madhrasaSp.decStuId > 0)
{
gridfillByNo();
MultiView1.ActiveViewIndex = 1;
}
else
{
MultiView1.ActiveViewIndex = 0;
Label1.Visible = true;
Label1.Text = "Invalid Register Number";
}
}
protected void Button2_Click(object sender, EventArgs e)
{
regSearch();
}
You Dont you just set the grid view's EmptyDataText to 'Reg No Dosent exist'. It will solve your ploblem.
<asp:GridView ID="GridView1" runat="server" EmptyDataText="register number not available">
</asp:GridView>

Resources