Insert Link Button In String Builder - c#

I created a dynamic link button, which needs to be inserted in a StringBuilder to not ruin the design of my aspx page.
So here's a "part" of my code where I need to insert my LinkButton:
design.Append("<h3>");
NewAddToCart(); //This is where my linkbutton should be inserted
design.Append("</h3></div>");
My NewAddToCart() is constructed on the following code:
private void NewAddToCart()
{
LinkButton lbtnAddtoCart = new LinkButton();
lbtnAddtoCart.ID = "lbtnCart" + i;
lbtnAddtoCart.CommandArgument = i.ToString();
lbtnAddtoCart.CssClass = "glyphicon glyphicon-shopping-cart pull-right";
lbtnAddtoCart.Click+=lbtnAddtoCart_Click;
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter html = new HtmlTextWriter(sw))
{
lbtnAddtoCart.RenderControl(html);
}
}
}

Related

How can I add dynamically a textBox value using ItextSharp?

Hi I'm using a ITextSharp to create a PDF. This is my code:
private void FillForm()
{
_path = HttpContext.Current.Server.MapPath("~/") + "\\PDF";
string formFile = _path + "\\Test.pdf";
string newFile = _path + "\\Test2.pdf";
var reader = new PdfReader(formFile);
using (var stamper = new PdfStamper(reader, new FileStream(newFile, FileMode.Create)))
{
AcroFields fields = stamper.AcroFields;
var conn = new SqlConnection(DataManager.ConnectionString);
conn.Open();
var command = new SqlCommand("SQLCommand"), conn);
var dt = new DataTable();
var adapter = new SqlDataAdapter(command);
adapter.Fill(dt);
int rowIndex = 1;
for (int i=0; i < dt.Rows.Count; i++)
{
var name = (string)dt.Rows[i]["Parameter"];
fields.SetField("txt_" + rowIndex, name);
rowIndex++;
}
stamper.FormFlattening = false;
stamper.Close();
}
}
I have a problem when I'm trying to fill the userName into textboxes. I have a list of names that I get it from the SQL query and I want to display it in different textboxes.
Only the first textBox display its value. For the others I must click on textBox to view the value inside.
Does anyone have any idea how I can fix it?
One line is missing in your code:
fields.GenerateAppearances = true;
You need to add this line right after:
AcroFields fields = stamper.AcroFields;
Why is this happening? Your template is somewhat wrong (maybe it was created using OpenOffice): it says that the software used to fill out the form shouldn't generate the appearances of the fields. As a result the value of the field is added (this is proven by the fact that the text appears when you click it), but the appearance is missing (hence the blank fields).

Adding item to DataGridView by clicking button using c#

I'm writing a program for manage all customers we have in our company. I have a DataGridView where every single customer should display. And right to the DataGridView I got some textboxes, for displaying the details of every customer and for add a new customer. And I got a button "Add Customer". So if I type in some random text in textboxes and click on "Add Customer" it should add the new customer to the DataGridView. And if I restart the program, every customer should still be saved. So I save the details of every customer to a .xml file.
Can someone help me or give me a hint how I can add customers to DataGridView by clicking button? I got this code for saving to xml file:
public partial class Form1 : Form
{
const string folder = #"C:\Users\Römel\Desktop\Save";
const string basename = "save.xml";
string filename = folder + "\\" + basename;
public Form1()
{
InitializeComponent();
if (Directory.Exists(folder))
{
if (File.Exists(filename))
{
DataSet flatDataSet = new DataSet();
flatDataSet.ReadXml(filename);
DataTable table = flatDataSet.Tables[0];
dataGridKunden.DataSource = table;
}
dataGridKunden.Columns["KundenNr"].Visible = false;
dataGridKunden.Columns["Adresse"].Visible = false;
dataGridKunden.Columns["Ort"].Visible = false;
dataGridKunden.Columns["Telefon"].Visible = false;
dataGridKunden.Columns["Mail"].Visible = false;
dataGridKunden.ScrollBars = ScrollBars.None;
}
}
private void btnAddKunde_Click(object sender, EventArgs e)
{
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
if (!File.Exists(filename))
{
File.Create(filename);
}
XmlTextWriter xwriter = new XmlTextWriter(filename, Encoding.Unicode);
xwriter.WriteStartDocument();
xwriter.WriteStartElement("Kundenverwaltung");
xwriter.WriteStartElement("KundenNr");
xwriter.WriteString(txtKundenNr.Text);
xwriter.WriteEndElement();
xwriter.WriteStartElement("Nachname");
xwriter.WriteString(txtKundeNachname.Text);
xwriter.WriteEndElement();
xwriter.WriteStartElement("Vorname");
xwriter.WriteString(txtKundeVorname.Text);
xwriter.WriteEndElement();
xwriter.WriteStartElement("Adresse");
xwriter.WriteString(txtKundeAdresse.Text);
xwriter.WriteEndElement();
xwriter.WriteStartElement("Ort");
xwriter.WriteString(txtKundeOrt.Text);
xwriter.WriteEndElement();
xwriter.WriteStartElement("Telefon");
xwriter.WriteString(txtKundeTel.Text);
xwriter.WriteEndElement();
xwriter.WriteStartElement("Mail");
xwriter.WriteString(txtKundeMail.Text);
xwriter.WriteEndElement();
xwriter.WriteEndDocument();
xwriter.Close();
}
}
The button "Add Customer" is called "btnAddKunde".
Thanks in advance.
Cheers
Add These line of code in your button click event in last:
if (File.Exists(filename))
{
DataSet flatDataSet = new DataSet();
flatDataSet.ReadXml(filename);
DataTable table = flatDataSet.Tables[0];
dataGridKunden.DataSource = table;
}
However, your version of XmlTextWriter will overwrite the xml file. Thus, when you click on button you will see only the latest added row. Instead you can use below code in your button click event:
private void btnAddKunde_Click(object sender, EventArgs e)
{
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
if (!File.Exists(filename))
{
using (File.Create(filename))
{}
}
XElement xmlNode = new XElement("Kundenverwaltung",
new XElement("KundenNr", txtKundenNr.Text),
new XElement("Nachname", txtKundeNachname.Text),
new XElement("Vorname", txtKundeVorname.Text),
new XElement("Adresse", txtKundeAdresse.Text),
new XElement("Ort", txtKundeOrt.Text),
new XElement("Telefon", txtKundeTel.Text),
new XElement("Mail", txtKundeMail.Text)
);
XElement xmlFile;
try
{
xmlFile = XElement.Load(filename);
xmlFile.Add(xmlNode);
}
catch (XmlException)
{
xmlFile = new XElement("Customers", xmlNode);
}
xmlFile.Save(filename);
DataSet flatDataSet = new DataSet();
flatDataSet.ReadXml(filename);
DataTable table = flatDataSet.Tables[0];
dataGridKunden.DataSource = table;
}
you need to use XMLDocument class to retrieve data from xml file
do something like this :
XDocument xmlDoc = XDocument.Load("People.xml");
xmlDoc.Element("employee").Add(new XElement("Person", new XElement("Name", txtName.Text),
new XElement("City", txtCity.Text), new XElement("Age", txtAge.Text)));
Are you lookin for an example for retrieving data from xml or just add string array retrieved from xml??
Here's how you add a string array..
string[] s = new string[4];
s[0] = "Salim";
s[1] = "9388938813"
s[2] = "s/10 santhi Nagar, Dpo road, Palakkad"
s[3] = "Kerala"
datagridView1.Rows.Add(s);
dataGridKunden.Rows.Add(new string[] {surname.text, forename.text, address.text .... });
// add as much as you want.

Barcode number under generated Barcode using Barcode Rendering Framework in web application

Following is my previous question that is working fine and generating the barcode.
My previous Question
Now, I just want the characters(forming the barcode) to be written under this barcode(image). How can i achieive that.? I am using Barcode Rendering Framework for generating the barcode. Please help.
Can I do it by taking a panel and adding the image and the text(barcode characters) and printing the panel.??
I did it by using asp panel in which i added the barcode image that is created. Under that I added the string i.e my barcode characters. Then using the print helper function I am able to print them.
Following is my code for adding image and text to panel.
Code39BarcodeDraw barcode39 = BarcodeDrawFactory.Code39WithoutChecksum;
// Panel pnl = new Panel();
Label str = new Label();
str.Text="SER1012308131";
// System.Drawing.Image img = barcode39.Draw("SER1012308131", 40);
//string path = Server.MapPath("~/Uploads/") + img+".jpeg";
string path = #"~/Uploads/abcd.jpeg";
// img.Save(path);
Image imgg = new Image();
imgg.ImageUrl=path;
pnlpnl.Width = Unit.Pixel(300);
pnlpnl.Height = Unit.Pixel(45);
pnlpnl.Controls.Add(imgg);
pnlpnl.Controls.Add(str);
Session["ctrl"] = pnlpnl;
ClientScript.RegisterStartupScript
(this.GetType(), "onclick", "<script language=javascript>window.open('Print.aspx','PrintMe','height=45px,width=300px,scrollbars=1');</script>");
Print helper function.
public PrintHelper()
{
}
public static void PrintWebControl(Control ctrl)
{
PrintWebControl(ctrl, string.Empty);
}
public static void PrintWebControl(Control ctrl, string Script)
{
StringWriter stringWrite = new StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
if (ctrl is WebControl)
{
Unit w = new Unit(100, UnitType.Percentage); ((WebControl)ctrl).Width = w;
}
Page pg = new Page();
pg.EnableEventValidation = false;
if (Script != string.Empty)
{
pg.ClientScript.RegisterStartupScript(pg.GetType(), "PrintJavaScript", Script);
}
HtmlForm frm = new HtmlForm();
pg.Controls.Add(frm);
frm.Attributes.Add("runat", "server");
frm.Controls.Add(ctrl);
pg.DesignerInitialize();
pg.RenderControl(htmlWrite);
string strHTML = stringWrite.ToString();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(strHTML);
HttpContext.Current.Response.Write("<script>window.print();</script>");
HttpContext.Current.Response.End();
}

How to dynamically generate html with .ascx?

I have some settings stored in web.config like this:
<add key="Answers" value="radiobutton1,radiobutton2,radiobutton3"/>
Radiobutton1, radiobutton2 and radiobutton3 are radiobutton label values.
In settings.cs I have a function to retrieve value from web.config:
public static string Answers
{
get
{
return System.Configuration.ConfigurationManager.AppSettings["Answers"];
}
}
.ascx file:
<table runat="server" OnPreRender="Radio_PreRender" id="table1" name="table1">
</table>
My ascx.cs file contains this function:
protected void Radio_PreRender(object sender, EventArgs e)
{
if (Settings.Answers != "")
{
int counter = 0;
string a = Settings.Answers;
string[] words = a.Split(',');
StringWriter stringwriter = new StringWriter();
HtmlTextWriter writer = new HtmlTextWriter(stringwriter);
foreach (string word in words)
{
writer.WriteBeginTag("tr");
writer.WriteBeginTag("td");
writer.Write("abc123");
RadioButton rdb1 = new RadioButton();
rdb1.Checked = true;
rdb1.GroupName = "rdbgroup";
rdb1.ID = "radiobutton" + counter;
rdb1.Text = word;
table1.Controls.Add(rdb1 );
writer.WriteEndTag("td");
writer.WriteBeginTag("tr");
table1.Render(writer);
counter++;
}
}
}
In other words, I want to generate a dynamic number of this code inside table1:
<tr>
<td>
// input type="radiobutton" and label go here.
</td>
</tr>
At the moment radiobuttons are not generated, because they can't be direct child elements to a table. If I specify a div instead, radiobuttons are generated, but everything I try to write with HtmlTextWriter is not. I understand that my html has to be rendered by using table1.Render(writer); or something similar, but I can't figure it out.
You can try creating a table and add it to the page you are working on, using the exmaple below you can replace the textbox with a radiobutton
Here is an example:
//Creat the Table and Add it to the Page
Table table = new Table();
table.ID = "Table1";
Page.Form.Controls.Add(table);
// Now iterate through the table and add your controls
for (int i = 0; i < rowsCount; i++)
{
TableRow row = new TableRow();
for (int j = 0; j < colsCount; j++)
{
TableCell cell = new TableCell();
TextBox tb = new TextBox();
// Set a unique ID for each TextBox added
tb.ID = "TextBoxRow_" + i + "Col_" + j;
// Add the control to the TableCell
cell.Controls.Add(tb);
// Add the TableCell to the TableRow
row.Cells.Add(cell);
}
// Add the TableRow to the Table
table.Rows.Add(row);
}
I do this quite often by running the user control through its full asp.net lifetime and getting it as a string:
http://www.diaryofaninja.com/blog/2009/09/14/a-simple-solution-to-viewing-a-preview-of-any-page-in-your-site
This way you can use ASP.Net as a templating engine for anything
Page tempPage = new Page();
UserControl myUserControl = new MyUserControl();
tempPage.Controls.Add(myUserControl);
StringWriter sw = new StringWriter();
HttpContext.Current.Server.Execute(tempPage, sw, false);
if (!String.IsNullOrEmpty(sw.ToString()))
{
return sw.ToString();
}

How can I get a server-side control's tag?

How can I get a server-side control's tag? I'm guessing it's something like below:
TextBox textBox=new TextBox();
GetTag(TextBox textBox)
{
...
}
And the result is something like <asp:TextBox /> (the control's design time tag).
When I change the control to CheckBox then the result should be something like <asp:CheckBox />.
There are no methods that can return these tags for you but constructing a dictionary your self should be easy enough.
Dictionary<Type, string> d = new Dictionary<Type, string>();
d.Add(typeof(TextBox), #"<\asp:TextBox />");
TextBox t = new TextBox();
string tag= (d[t.GetType()]);
And so on...
You can use RenderControl method
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
{
using (HtmlTextWriter textWriter = new HtmlTextWriter(sw))
{
textBox.RenderControl(textWriter);
}
}
sb will have textBox's html content.
Edit:
You can get aspx content and find element tag. like this:
String path = Server.MapPath("~/[aspx path]");
string content = File.ReadAllText(path);
string controlID = "textBox";
int startIndex = content.IndexOf("<asp:TextBox ID=\"" + controlID + "\"");
bool foundEndTag = false;
string controlTag = "";
int i = startIndex;
while (!foundEndTag)
{
if (content[i] == '>')
foundEndTag = true;
controlTag += content[i];
i++;
}

Categories