How can I get link to include mailto: in aspx file? - asp.net

<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;

Related

Grid View Row Data Bound event

I can't run on IIS Server. I write with dynamically create link button in gridvew row data bound and Link button can't redirect access to file server. I only can on visual studio. Please let me know, how to solve it.
protected void GVSample_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.`enter code here`RowType == DataControlRowType.DataRow)
{
string variable = e.Row.Cells[8].Text.ToString();
string[] stringSeparators = { ";" };
string[] result;
result = variable.Split(stringSeparators, StringSplitOptions.None);
foreach (string s in result)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lb = new LinkButton();
lb.Text = s.ToString() + "<br />";
lb.CommandName = "ApproveVacation";
lb.Command += LinkButton_Command;
e.Row.Cells[8].Controls.Add(lb);
}
}
}
}
protected void LinkButton_Command(object sender, CommandEventArgs e)
{
string val = ((LinkButton)sender).Text;
int row = -1;
int.TryParse(e.CommandArgument as string, out row);
if (row == -1)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "displayalertmessage", "alert('Fail to Open File');", true);
return;
}
GridViewRow gdrow = GridView1.Rows[row];
DataRow dr = ((DataTable)this.GridView1.DataSource).Rows[gdrow.DataItemIndex];
if (e.CommandName == "ApproveVacation")
{
try
{
string username = "Bla";
string password = "bla";
System.Net.NetworkCredential readCredentials = new NetworkCredential(username, password);
string filepath = #"\\192.168.1.100\SAPAttachments\abc";
using (new NetworkConnection(filepath, readCredentials))
{
WebClient User = new WebClient();
string file = ((LinkButton)sender).Text;
string a = #"<br />";
file = file.Replace(a, "");
foreach (var item in file)
{
Byte[] FileBuffer = User.DownloadData(file);
string stringCutted = file.Substring(file.LastIndexOf(".") + 1);
if (stringCutted == "docx" || stringCutted == "DOCX")
{
if (FileBuffer != null)
{
Context.Response.Clear();
FileInfo Sourcefile = new FileInfo(file);
Context.Response.ContentType = "Application/msword";
Context.Response.AppendHeader("Content-Disposition", "inline; filename=" + Sourcefile.Name);
Context.Response.AppendHeader("Content-Length", Sourcefile.Length.ToString());
Context.Response.WriteFile(Sourcefile.FullName);
Context.Response.End();
}
}
if (stringCutted == "pdf" || stringCutted == "PDF")
{
if (FileBuffer != null)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", FileBuffer.Length.ToString());
Response.BinaryWrite(FileBuffer);
Response.End();
}
}
if (stringCutted == "jpg" || stringCutted == "JPG" || stringCutted == "jpeg" || stringCutted == "JPEG")
{
if (FileBuffer != null)
{
Response.ContentType = "image/jpeg";
Response.AddHeader("content-length", FileBuffer.Length.ToString());
Response.BinaryWrite(FileBuffer);
Response.End();
}
}
}
ScriptManager.RegisterStartupScript(this, this.GetType(), "displayalertmessage", "alert('Success');", true);
}
}
catch
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "displayalertmessage", "alert('Fail to Open File');", true);
}
}
}

Writing to a text file using ASP

Im totally new to ASP so any help would be very grateful. I have a html page which has a form for users to leave their details and when they submit it goes to a text file fine but what I want is once they have submitted it I want to have an alert saying "comment saved" and to stay on the original page so they can submit another if they choose but when the user submits it goes to a blank page.
My Form is
<form method="post" action="comments.asp">
<br><br>
Age <input type="text" name="age" />
Name<textarea rows="1" cols="70" <input type="text" name="name" /></textarea>
<input type="submit" value="Send Comment">
</form>
my comments.asp file code is
<%
Dim age, name
age = Request.Form("age")
name = Request.Form("name")
dim fs,f
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.OpenTextFile("C:\Inetpub\wwwroot\Wiki\Comments.txt",8,true)
f.WriteLine(age & " " & date() & " " & name)
f.Close
set f=nothing
set fs=nothing
%>
<%
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
'Open the file for writing
Set f = fso.CreateTextFile(s_path & "/" & s_file_being_created, True)
f.Write(m)
f.Close
Set f = Nothing
Set fso = Nothing
%>
For those of you writing ASP with JScript instead of VBS, the code might look something like this:
var fileSystemObject = Server.CreateObject("Scripting.FileSystemObject");
var textStream = fileSystemObject.CreateTextFile(filePath, true, true);
textStream.Write(fileContent);
textStream.Close();
delete textStream;
delete fileSystemObject;
Documentation references:
Scripting.FileSystemObject object
FileSystemObject.CreateTextFile() method
TextStream object
Write() method
Close() method
delete operator
namespace A6
{
public partial class imanik : System.Web.UI.Page
{
public class RedTabele {
public string sifra { get; set; }
public string ime { get; set; }
public string prezime { get; set; }
public string adresa { get; set; }
public string mesto { get; set; }
public string broj { get; set; }
public string mail { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
// Lista za mesta
List<string> mesta = new List<string>();
using (StreamReader sr = new StreamReader(Server.MapPath("imenik.txt")))
{
string line;
while ((line = sr.ReadLine()) != null)
{
/* line = Шифра корисника | Име | Презиме | Адреса | Место | Број телефона | e-mail */
string[] podeljeno = line.Split('|');
string mesto = podeljeno[4];
mesto = mesto.Trim();
mesta.Add(mesto);
}
}
List<string> bezDuplikata = mesta.Distinct().ToList();
for (int i = 0; i < bezDuplikata.Count; i++)
{
ListaMesto.Items.Add(bezDuplikata[i]);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
// sakri i ocisti table
Table1.Rows.Clear();
Table1.Visible = false;
// uzimanje podataka iz txtboxova
string ime = txtIme.Text;
string prezime = txtPrezime.Text;
string adresa = txtAdresa.Text;
string mesto = ListaMesto.Text;
string br = txtTel.Text;
// lista rezultata
// Gore smo napravili klasu za ovo
List<RedTabele> rezultati = new List<RedTabele>();
using (StreamReader sr = new StreamReader(Server.MapPath("imenik.txt")))
{
string line;
while ((line = sr.ReadLine()) != null)
{
/* line = Шифра корисника | Име | Презиме | Адреса | Место | Број телефона | e-mail */
string[] podeljeno = line.Split('|');
string sifraTXT = podeljeno[0];
string imeTXT = podeljeno[1];
string prezimeTXT = podeljeno[2];
string adresaTXT = podeljeno[3];
string mestoTXT = podeljeno[4];
string brTXT = podeljeno[5];
string mailTXT = podeljeno[6];
sifraTXT = sifraTXT.Trim();
imeTXT = imeTXT.Trim();
prezimeTXT = prezimeTXT.Trim();
adresaTXT = adresaTXT.Trim();
mestoTXT = mestoTXT.Trim();
brTXT = brTXT.Trim();
mailTXT = mailTXT.Trim();
bool ImeOk = true;
bool PrezimeOk = true;
bool AdresaOk = true;
bool MestoOk = true;
bool BrOk = true;
if (ime != "") {
ImeOk = imeTXT.StartsWith(ime);
}
if (prezime != "")
{
PrezimeOk = prezimeTXT.StartsWith(prezime);
}
if (adresa != "")
{
AdresaOk = adresaTXT.StartsWith(adresa);
}
if (br != "")
{
BrOk = brTXT.StartsWith(br);
}
if (mesto != mestoTXT)
MestoOk = false;
if (ImeOk && PrezimeOk && AdresaOk && MestoOk && BrOk)
{
rezultati.Add(new RedTabele {
sifra = sifraTXT,
ime = imeTXT,
prezime = prezimeTXT,
adresa = adresaTXT,
mesto = mestoTXT,
broj = brTXT,
mail = mailTXT
});
}
}
// Create Table
TableRow naslovna = new TableRow();
Table1.Rows.Add(naslovna);
TableCell tdSifra = new TableCell();
tdSifra.Text = "Sifra";
TableCell tdIme = new TableCell();
tdIme.Text = "Ime";
TableCell tdPrezime = new TableCell();
tdPrezime.Text = "Prezime";
TableCell tdAdresa = new TableCell();
tdAdresa.Text = "Adresa";
TableCell tdMesto = new TableCell();
tdMesto.Text = "Mesto";
TableCell tdBroj = new TableCell();
tdBroj.Text = "Broj";
TableCell tdMail = new TableCell();
tdMail.Text = "Mail";
naslovna.Cells.Add(tdSifra);
naslovna.Cells.Add(tdIme);
naslovna.Cells.Add(tdPrezime);
naslovna.Cells.Add(tdAdresa);
naslovna.Cells.Add(tdMesto);
naslovna.Cells.Add(tdBroj);
naslovna.Cells.Add(tdMail);
for (int i = 0; i < rezultati.Count; i++) {
TableRow red = new TableRow();
TableCell sifraKol = new TableCell();
TableCell imeKol = new TableCell();
TableCell prezimeKol = new TableCell();
TableCell adresaKol = new TableCell();
TableCell mestoKol = new TableCell();
TableCell brojKol = new TableCell();
TableCell mailKol = new TableCell();
sifraKol.Text = rezultati[i].sifra;
imeKol.Text = rezultati[i].ime;
prezimeKol.Text = rezultati[i].prezime;
adresaKol.Text = rezultati[i].adresa;
mestoKol.Text = rezultati[i].mesto;
brojKol.Text = rezultati[i].broj;
mailKol.Text = rezultati[i].mail;
red.Controls.Add(sifraKol);
red.Controls.Add(imeKol);
red.Controls.Add(prezimeKol);
red.Controls.Add(adresaKol);
red.Controls.Add(mestoKol);
red.Controls.Add(brojKol);
red.Controls.Add(mailKol);
Table1.Rows.Add(red);
}
Table1.Visible = true;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
// Za tekstualne fajlove
using System.IO;
namespace A6
{
public partial class imanik : System.Web.UI.Page
{
public class RedTabele
{
public string sifra { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
List<string> mesta = new List<string>();
using (StreamReader sr = new StreamReader(Server.MapPath("imenik.txt")))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string[] podeljeno = line.Split('|');
string mesto = podeljeno[4];
mesto = mesto.Trim();
mesta.Add(mesto);
}
}
List<string> bezDuplikata = mesta.Distinct().ToList();
for (int i = 0; i < bezDuplikata.Count; i++)
{
ListaMesto.Items.Add(bezDuplikata[i]);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Table1.Rows.Clear();
Table1.Visible = false;
string ime = txtIme.Text;
string prezime = txtPrezime.Text;
string adresa = txtAdresa.Text;
string mesto = ListaMesto.Text;
string br = txtTel.Text;
List<RedTabele> rezultati = new List<RedTabele>();
using (StreamReader sr = new StreamReader(Server.MapPath("imenik.txt")))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string[] podeljeno = line.Split('|');
string sifraTXT = podeljeno[0];
sifraTXT = sifraTXT.Trim();
bool ImeOk = true;
bool PrezimeOk = true;
bool AdresaOk = true;
bool MestoOk = true;
bool BrOk = true;
if (ime != "")
{
ImeOk = imeTXT.StartsWith(ime);
}
if (ImeOk && PrezimeOk && AdresaOk && MestoOk && BrOk)
{
rezultati.Add(new RedTabele
{
sifra = sifraTXT,
});
}
}
// Create Table
TableRow naslovna = new TableRow();
Table1.Rows.Add(naslovna);
TableCell tdSifra = new TableCell();
tdSifra.Text = "Sifra";
naslovna.Cells.Add(tdSifra);
for (int i = 0; i < rezultati.Count; i++)
{
TableRow red = new TableRow();
TableCell sifraKol = new TableCell();
sifraKol.Text = rezultati[i].sifra;
red.Controls.Add(sifraKol);
Table1.Rows.Add(red);
}
Table1.Visible = true;
}
}
}
}

dropdownlist index changed value

I have a problem when I change dropdownlist1 item, The changed item not being accessed on the event of DropDownList1_SelectedIndexChanged.
Here is my code...
namespace My_News.Views.Shared
{
public partial class Master : System.Web.UI.MasterPage
{
SqlDataReader dr;
string user_id = "";
protected void Page_Load(object sender, EventArgs e)
{
/* user login information */
if (Session["status"] != null)
{
Button1.Text = "Logout";
Button2.Visible = true; ;
Button2.Text = Session["name"] as string + "'s Profile";
Button3.Enabled = true;
DropDownList1.Enabled = true;
user_id = Session["reg_id"] as string;
DropDownList1.Items.Clear();
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection_String"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT DISTINCT[news_category] from [news_profile] WHERE [user_id]='" + user_id + "'";
cmd.Connection = connection;
connection.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
DropDownList1.Items.Add(dr[0].ToString());
}
connection.Close();
}
}
}
else
{
Button1.Text = "Login";
Button2.Visible = false;
Button3.Enabled = false;
DropDownList1.Enabled = false;
Session.Clear();
}
}
Dropdownnlist index change event...
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Session["news_category"] = DropDownList1.Text;
Session["reload"] = "yes";
Session.Timeout = 10;
Response.Redirect("Default.aspx");
}
}
}
Please help me.
You need to modify your code like this
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
bindDDL();
}
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
string s = ddl.Text;
}
public void bindDDL()
{
DataTable dt = new DataTable("Drop");
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(1, "ABCD");
dt.Rows.Add(2, "EFGH");
ddl.DataSource = dt;
ddl.DataValueField = "ID";
ddl.DataTextField = "Name";
ddl.DataBind();
}

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

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 .

how to delete dynamic control(textbox and button) when user click delete button

this is my code and i want to know how i add some code to delete dynamic control(textbox and button) when user click delete button. Please help me T_T
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
CreateTextBox();
}
else
{
Session["arrayTextBox"] = null;
Session["arrayButton"] = null;
}
}
protected void CreateTextBox()
{
List<TextBox> arrayTextBox = new List<TextBox>();
List<Button> arrayButton = new List<Button>();
if (TextBox1.Text != "")
{
if (Session["arrayTextBox"] != null)
{
arrayTextBox = (List<TextBox>)Session["arrayTextBox"];
arrayButton = (List<Button>)Session["arrayButton"];
}
TextBox aTextBox = new TextBox();
aTextBox.ID = "aTextBox" + arrayTextBox.Count.ToString();
aTextBox.Text = TextBox1.Text;
Button ButtonDelete = new Button();
ButtonDelete.ID = "ButtonDelete" + arrayButton.Count.ToString();
ButtonDelete.Text = "Delete";
//if (TextBox2.Text != "")
//{
// String red = TextBox2.Text.ToString().Substring(0, 2);
// String green = TextBox2.Text.ToString().Substring(2, 2);
// String blue = TextBox2.Text.ToString().Substring(4, 2);
// int r = int.Parse(red, NumberStyles.AllowHexSpecifier);
// int g = int.Parse(green, NumberStyles.AllowHexSpecifier);
// int b = int.Parse(blue, NumberStyles.AllowHexSpecifier);
// aTextBox.BackColor = System.Drawing.Color.FromArgb(r, g, b);
//}
arrayTextBox.Add(aTextBox);
arrayButton.Add(ButtonDelete);
for(int i=0;i<arrayTextBox.Count;i++)
{
PlaceHolder1.Controls.Add(arrayTextBox[i]);
PlaceHolder1.Controls.Add(arrayButton[i]);
PlaceHolder1.Controls.Add(new LiteralControl(#"<br />"));
}
//ButtonDelete.Click += new EventHandler(ButtonDelete_Click);
Session["arrayTextBox"] = arrayTextBox;
Session["arrayButton"] = arrayButton;
TextBox1.Text = "";
//TextBox2.Text = "";
}
}
}
foreach the arrayTextBox and get TextBox, then use PlaceHolder1.Controls.Remove(Textbox)
You can use the code below.
Note: I used CommandArgument of the button to store the id of corresponding textbox and then use Page.Controls.Remove in the btn click event:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
CreateTextBox();
}
else
{
Session["arrayTextBox"] = null;
Session["arrayButton"] = null;
}
}
protected void ButtonDelete_Click(object Sender, EventArgs e)
{
Button btn = Sender as Button;
if(btn != null)
{
String szTextControlID = btn.CommandArgument;
Control ctl = Page.FindControl(szTextControlID);
Page.Controls.Remove(ctl);
Page.Controls.Remove(btn);
}
}
protected void CreateTextBox()
{
List<TextBox> arrayTextBox = new List<TextBox>();
List<Button> arrayButton = new List<Button>();
if (TextBox1.Text != "")
{
if (Session["arrayTextBox"] != null)
{
arrayTextBox = (List<TextBox>)Session["arrayTextBox"];
arrayButton = (List<Button>)Session["arrayButton"];
}
TextBox aTextBox = new TextBox();
aTextBox.ID = "aTextBox" + arrayTextBox.Count.ToString();
aTextBox.Text = TextBox1.Text;
Button ButtonDelete = new Button();
ButtonDelete.ID = "ButtonDelete" + arrayButton.Count.ToString();
ButtonDelete.CommandArgument = aTextBox.ID;
ButtonDelete.Text = "Delete";
ButtonDelete.Click += new EventHandler(ButtonDelete_Click);
//if (TextBox2.Text != "")
//{
// String red = TextBox2.Text.ToString().Substring(0, 2);
// String green = TextBox2.Text.ToString().Substring(2, 2);
// String blue = TextBox2.Text.ToString().Substring(4, 2);
// int r = int.Parse(red, NumberStyles.AllowHexSpecifier);
// int g = int.Parse(green, NumberStyles.AllowHexSpecifier);
// int b = int.Parse(blue, NumberStyles.AllowHexSpecifier);
// aTextBox.BackColor = System.Drawing.Color.FromArgb(r, g, b);
//}
arrayTextBox.Add(aTextBox);
arrayButton.Add(ButtonDelete);
for(int i=0;i<arrayTextBox.Count;i++)
{
PlaceHolder1.Controls.Add(arrayTextBox[i]);
PlaceHolder1.Controls.Add(arrayButton[i]);
PlaceHolder1.Controls.Add(new LiteralControl(#"<br />"));
}
Session["arrayTextBox"] = arrayTextBox;
Session["arrayButton"] = arrayButton;
TextBox1.Text = "";
//TextBox2.Text = "";
}
}

Resources