Writing to a text file using ASP - asp-classic

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

Related

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;

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 .

In ASP.net ".aspx" pages placed in subfolder can not access when in click on that specific page in menu

i am using jquery menu on master page. menu containt bind at runtime depend upon user right.
in my project ".aspx" pages placed in root folder as well as subfolder ..when i click on page name on menu it redirect me to that specific page which is located in root part of my project.
but i can't redirect to pages in subfolder..
target page name is defined in database. on clicking it pick up target url from datatbse and redirect to page.
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using AjaxPro;
public partial class Reports_fleet : System.Web.UI.MasterPage
{
Jetfleet_Framework.clsDataAcess objData = new Jetfleet_Framework.clsDataAcess();
DataSet dsMenu = new DataSet();
HttpBrowserCapabilities objbrowser;
protected void Page_Load(object sender, EventArgs e)
{
objbrowser = Request.Browser;
if (objbrowser.Browser == "AppleMAC-Safari")
{
loctbl.Style.Add("margin-top", "30px");
loctbl.Style.Add("margin-left", "-30px");
sumnu.Style.Add("margin-top", "2px");
}
if (objbrowser.Browser == "Firefox")
{
loctbl.Style.Add("margin-top", "30px");
loctbl.Style.Add("margin-left", "-50px");
sumnu.Style.Add("margin-top", "2px");
}
lbl.Text = Session["ServiceLocName"].ToString();
hdnRelease.Value = Session["Release"].ToString();
hdnCloseWindow.Value = Session["userId"].ToString();
Utility.RegisterTypeForAjax(typeof(Reports_fleet));
Response.Buffer = true;
Response.ExpiresAbsolute = DateTime.Now.AddDays(-1d);
Response.Expires = -1500;
Response.Cache.SetNoStore();
Response.CacheControl = "no-cache";
if (Session["userId"] == null)
{
Response.Redirect("LogIn.aspx");
}
//name.InnerHtml = Session["userFullName"].ToString();
BuildNavigationMenu();
name.InnerHtml = Session["userFullName"].ToString();
if (!this.IsPostBack)
{
if (Session["Release"] == "True")
{
string spRelease = "usp_ins_upd_task_assign;3";
Object[] paramRelease = new Object[1];
paramRelease[0] = (Object)Session["userId"].ToString();
objData.ExecuteNonQuery(spRelease, paramRelease);
}
else
{
Session["Release"] = "True";
}
}
}
private void BuildNavigationMenu()
{
//Creates html UL element for menu.
string uname = "", pass = "", location = "";
Session["bchk"] = "True";
int userId = System.Int32.Parse(Session["userId"].ToString());
int roleId = System.Int32.Parse(Session["userRole"].ToString());
try
{
if (Session["navigation_menu_dataset"] != null)
{
dsMenu = (DataSet)Session["navigation_menu_dataset"];
}
else
{
dsMenu = GetNavigationMenu(userId, roleId);
Session["navigation_menu_dataset"] = dsMenu;
}
uname = Session["userName"].ToString();
pass = Session["password"].ToString();
location = Session["loction"].ToString();
Session["username"] = uname;
Session["password"] = pass;
Session["Location"] = location;
int mnuCount, totalMenus;
totalMenus = System.Int32.Parse(dsMenu.Tables[1].Rows[0]["total_menus"].ToString());
HtmlGenericControl divMenu = new HtmlGenericControl("div");
divMenu.Attributes["id"] = "menu";
HtmlGenericControl ulMenu = new HtmlGenericControl("ul");
ulMenu.Attributes["class"] = "menu";
for (mnuCount = 1; mnuCount <= totalMenus; mnuCount++)
{
HtmlGenericControl liMain = new HtmlGenericControl("li");
if (mnuCount == totalMenus)
{
liMain.Attributes["class"] = "last";
}
else
{
liMain.Attributes["class"] = "parent";
}
HtmlGenericControl aMain = new HtmlGenericControl("a");
aMain.Attributes["href"] = "#";
HtmlGenericControl spMenu = new HtmlGenericControl("span");
DataRow[] drMenu = null;
drMenu = dsMenu.Tables[0].Select("parent_menu_id = " + mnuCount);
if (drMenu.Length != 0)
{
spMenu.InnerHtml = drMenu[0]["parent_menu_name"].ToString();//Masters
aMain.Controls.Add(spMenu);
liMain.Controls.Add(aMain);
HtmlGenericControl divMenu1 = new HtmlGenericControl("div");
HtmlGenericControl ulMenu1 = new HtmlGenericControl("ul");
int subMenuStepTo = 0;
for (int rowcnt = 0; rowcnt < drMenu.Length; rowcnt++)
{
if (drMenu[rowcnt]["is_folder"].ToString().ToLower() == "false")
{
//If no submenus are there.
HtmlGenericControl liMain1 = new HtmlGenericControl("li");//Booking Upload
HtmlGenericControl aMain1 = new HtmlGenericControl("a");
aMain1.Attributes["href"] = drMenu[rowcnt]["target_url"].ToString();
HtmlGenericControl spMenu1 = new HtmlGenericControl("span");
spMenu1.InnerHtml = " " + drMenu[rowcnt]["display_text"].ToString();
aMain1.Controls.Add(spMenu1);
liMain1.Controls.Add(aMain1);
ulMenu1.Controls.Add(liMain1);
}
if (drMenu[rowcnt]["is_folder"].ToString().ToLower() == "true")
{
//submenus are there
DataRow[] drSubMenu;
HtmlGenericControl liMain1 = new HtmlGenericControl("li");//Customer
liMain1.Attributes["class"] = "parent";
HtmlGenericControl aMain1 = new HtmlGenericControl("a");
aMain1.Attributes["href"] = "#";
HtmlGenericControl spMenu1 = new HtmlGenericControl("span");
subMenuStepTo = rowcnt;
spMenu1.InnerHtml = " " + drMenu[subMenuStepTo]["display_name"].ToString(); //subMenuStepTo
aMain1.Controls.Add(spMenu1);
liMain1.Controls.Add(aMain1);
drSubMenu = dsMenu.Tables[0].Select("display_name = '" + drMenu[subMenuStepTo]["display_name"].ToString() + "' AND parent_menu_id = " + mnuCount);//subMenuStepTo
HtmlGenericControl divMenu2 = new HtmlGenericControl("div");
HtmlGenericControl ulMenu2 = new HtmlGenericControl("ul");
for (int rowcnt1 = 0; rowcnt1 < drSubMenu.Length; rowcnt1++)
{
if (mnuCount == 3)
{
AppRelativeTemplateSourceDirectory = "~/Reports";
}
HtmlGenericControl liMain2 = new HtmlGenericControl("li");//Corporate
HtmlGenericControl aMain2 = new HtmlGenericControl("a");
aMain2.Attributes["href"] = drSubMenu[rowcnt1]["target_url"].ToString();
HtmlGenericControl spMenu2 = new HtmlGenericControl("span");
spMenu2.InnerHtml = " " + drSubMenu[rowcnt1]["display_text"].ToString();
aMain2.Controls.Add(spMenu2);
liMain2.Controls.Add(aMain2);
ulMenu2.Controls.Add(liMain2);
}
subMenuStepTo = subMenuStepTo + (drSubMenu.Length - 1);
divMenu2.Controls.Add(ulMenu2);
liMain1.Controls.Add(divMenu2);
ulMenu1.Controls.Add(liMain1);
}
if (drMenu[rowcnt]["is_folder"].ToString().ToLower() != "false")
{
rowcnt = subMenuStepTo;
}
}
divMenu1.Controls.Add(ulMenu1);
liMain.Controls.Add(divMenu1);
}
ulMenu.Controls.Add(liMain);
}
divMenu.Controls.Add(ulMenu);
mnuContainer.Controls.Add(divMenu);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
dsMenu.Dispose();
}
}
private DataSet GetNavigationMenu(int userId, int roleId)
{
//Gets menu items based on user id.
try
{
string spMenu = "usp_get_navigation_menu;2";
Object[] paramsMenu = new object[2];
paramsMenu[0] = (Object)userId;
paramsMenu[1] = (Object)roleId;
objData.FillDataset(spMenu, dsMenu, null, paramsMenu);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
objData.Dispose();
}
return dsMenu;
}
[AjaxPro.AjaxMethod]
public void CloseWindow(int userid, string release)
{
if (release == "False")
{
string spRelease = "usp_ins_upd_task_assign;3";
Object[] paramRelease = new Object[1];
paramRelease[0] = (Object)userid;
objData.ExecuteNonQuery(spRelease, paramRelease);
}
}
}
this is my code to bind menu at runtime ..i can't access subfolder pages ..i tried to define subfolder path in database ..it works at first time but when i click on other menu
page which is in root then in address bar ".aspx" page name attach with subfolder name
...so page could not found
please help me .........
use "< base href='http://localhost/testapp/' />" in master page, it will help you..

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 = "";
}
}

GridView Create Fields Dynamically

I would like somebody to help me to solve the following issue.
I have a gridview, where the fields are created dynamically from codebehind.
I would like to create with the same way(dynamically) a templateField which, if it is possible, to hold in it two button controls, having also and commandName.
To be more clear:
Headers-->> First Name, LastName, Print(Daily/Invoices)
Results -->> FooFName, FooLName, Daily | Invoice
The bold one text is what I am looking for.
I am posting also the methods and the way I use them to create the fields.
CreateBoundField(BillingSummaryGV, "Book_Date", "Date", "{0:dd/MM/yyyy}");
CreateButtonField(BillingSummaryGV, "Print", "Print(Daily)", ButtonType.Link,"");
BillingSummaryGV.DataSource = billingSummaries;
BillingSummaryGV.DataBind();
protected void CreateBoundField(GridView gv, string dataField, string headerText, string arrFormatingString) {
var bf = new BoundField {
DataField = dataField,
DataFormatString = arrFormatingString,
HeaderText = headerText
};
gv.Columns.Add(bf);
}
private void CreateButtonField(GridView gv, string text, string headerText, ButtonType buttonType, string commandName) {
var bfPrint = new ButtonField() {
ButtonType = buttonType,
Text = text,
HeaderText = headerText,
Visible = true,
CommandName = commandName
};
gv.Columns.Add(bfPrint);
}
I would appreciate any reply
thanks
You have to create a template class that implements ITemplate. See this example from MSDN. The code below extends my answer to this question to add a template column that displays Title|Author.
Markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
OnRowCommand="GridView1_RowCommand"
OnRowEditing="GridView1_RowEditing"/>
Code:
protected void Page_Load(object sender, EventArgs e)
{
BindGridView();
}
private DataTable GetBooksDataTable()
{
var dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Title", typeof(string));
dt.Columns.Add("Author", typeof(string));
for (int index = 0; index < 10; index++)
{
dt.Rows.Add(index, "Title" + index, "Author" + index);
}
return dt;
}
private void BindGridView()
{
var dt = GetBooksDataTable();
GridView1.Columns.Clear();
GridView1.ShowFooter = true;
var cf = new CommandField();
cf.HeaderText = "Action";
cf.ShowEditButton = true;
GridView1.Columns.Add(cf);
for (int index = 0; index < dt.Columns.Count; index++)
{
var boundField = new BoundField();
boundField.DataField = dt.Columns[index].ColumnName;
boundField.HeaderText = dt.Columns[index].ColumnName;
GridView1.Columns.Add(boundField);
}
CreateCustomTemplateField(GridView1, "Title|Author");
GridView1.DataSource = dt;
GridView1.DataBind();
var footer = GridView1.FooterRow;
var b = new LinkButton();
b.Text = "Add New";
b.CommandName = "Add New";
footer.Cells[0].Controls.Add(b);
for (int index = 1; index < dt.Columns.Count + 1; index++)
{
var tb = new TextBox();
footer.Cells[index].Controls.Add(tb);
}
}
private void CreateCustomTemplateField(GridView gv, string headerText)
{
var customField = new TemplateField();
customField.HeaderTemplate = new CustomTemplate(DataControlRowType.Header, headerText);
customField.ItemTemplate = new CustomTemplate(DataControlRowType.DataRow, headerText);
gv.Columns.Add(customField);
}
public class CustomTemplate : ITemplate
{
private DataControlRowType _rowType;
private string _headerText;
public CustomTemplate(DataControlRowType rowType, string headerText)
{
_rowType = rowType;
_headerText = headerText;
}
public void InstantiateIn(Control container)
{
switch (_rowType)
{
case DataControlRowType.Header:
var header = new Literal();
header.Text = _headerText;
container.Controls.Add(header);
break;
case DataControlRowType.DataRow:
var data = new Literal();
data.DataBinding += DataRowLiteral_DataBinding;
container.Controls.Add(data);
break;
}
}
private void DataRowLiteral_DataBinding(object sender, EventArgs e)
{
var data = (Literal)sender;
var row = (GridViewRow)data.NamingContainer;
data.Text = DataBinder.Eval(row.DataItem, "Title") + "|" + DataBinder.Eval(row.DataItem, "Author");
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
Literal1.Text = e.CommandName;
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
Literal1.Text = "Editing row index " + e.NewEditIndex.ToString();
}

Resources