Getting/Setting Select Box in Literal from ASP.Net Code-Behind - c#

I have the below code that gets added to a literal in my form. How in the code behind to I grab get/set the data from the select = name="populationSelect"....?
protected void PopulatePopulation()
{
StringBuilder sb = new StringBuilder();
StringBuilder sql = new StringBuilder();
// Define sql
sql.Append("SELECT pid, population ");
sql.Append("FROM populations ");
sql.Append("ORDER BY pid ASC ");
using (IDataReader reader = SqlHelper.GetDataReader(sql.ToString()))
{
sb.AppendLine("<div class=\"narrowRes\">Poulation</div><select name=\"populationSelect\" class=\"narrowResSelect\"><option value=\"0\">All populations</option>");
while (reader.Read())
{
int pid = reader.IsDBNull(0) ? -1 : reader.GetInt32(0);
string population = reader.IsDBNull(1) ? string.Empty : reader.GetString(1);
population = population.Trim();
sb.AppendLine(string.Format("<option value=\"{0}\">{1}</option>", pid, population));
}
}
sb.AppendLine("</select>");
ltrlExplorePopulation.Text = sb.ToString();
}

Not easily. Since you're using a literal instead of an asp.net control (like a drop down list), asp.net does not create a control for you to use in the code behind.
That being said you should be able to access the value through the Request parameters.
var value = Request["populationSelect"];
A better solution would be to create a dropdownlist control on the page and databind to it.
if (!IsPostBack)
{
List<ListItem> data = new List<ListItem>();
using (IDataReader reader = SqlHelper.GetDataReader(sql.ToString()))
{
//sb.AppendLine("<div class=\"narrowRes\">Poulation</div><select name=\"populationSelect\" class=\"narrowResSelect\"><option value=\"0\">All populations</option>");
while (reader.Read())
{
int pid = reader.IsDBNull(0) ? -1 : reader.GetInt32(0);
string population = reader.IsDBNull(1) ? string.Empty : reader.GetString(1);
population = population.Trim();
data.Add(new ListItem(population, pid.ToString()));
//sb.AppendLine(string.Format("<option value=\"{0}\">{1}</option>", pid, population));
}
}
DropDownList1.DataSource = data;
DropDownList1.DataBind();
}

Related

Compare text file data with database records in C#

I have to make a select statement on a database and than compare the results with a text file using only C# in Visual Studio. If the text file has a bigger value than the record in the database, the program returns the value from the text file, and if the database record has a bigger value, the program returns the value from the database. The results are added to a list being a class WynikPorownania{}. The user types in the file an index of a product and the value(in this case the value is it's availability condition).
For example:
The textfile says this:
WYR_WR_CZ1=12
VIDIS_JIMU_BOX=3
REREK_KOTEK_T=5
In the database, theses indexes are connected to an availability condition like this
WYR_WR_CZ1=-1.0000
VIDIS_JIMU_BOX=-13.0000
REREK_KOTEK_T=0.0000
Now the program should return the bigger value in a list being the WynikPorownania{} class.
For now, I managed to do this much: I took every record from the select query and put it in to a list as a class. I have a function that checks the "standysp"(availability condition) for a specified index, and I asigned the text file value to a string. I think that it could be done maybe with this "zwr" function and maybe a loop but I don't really know where to go from now on. This is my code for now:
using System;
using FirebirdSql.Data.FirebirdClient;
using System.Collections.Generic;
using System.Linq;
using System.IO;
namespace dokselect
{
class indexstan
{
public string index;
public double standysp;
}
class WynikPorownania
{
public string Indeks;
public int Ilosc;
}
class Program
{
public static void Main()
{
///////CONNECTION
string conn = "database=C:/PCBiznes/BAZA/IXION2_LOGMAG.FB;user=SYSDBA;password=masterkey;DataSource=192.168.24.112;Port=3050";
FbConnection myConnection = new FbConnection(conn);
FbDataReader myReader = null;
string sql = "select KARTOTEKA.indeks,STANMAG.standysp FROM kartoteka JOIN stanmag using(ID_KARTOTEKA);";
FbCommand myCommand = new FbCommand(sql, myConnection);
myConnection.Open();
myReader = myCommand.ExecuteReader();
///////LIST lista1
List<indexstan> lista1 = new List<indexstan>();
double standysp;
string index;
while (myReader.Read())
{
index = myReader[0].ToString();
standysp = Convert.ToDouble(myReader[1]);
lista1.Add(new indexstan { index=index, standysp=standysp });
//Console.WriteLine(myReader[0].ToString());
}
myConnection.Close();
Console.WriteLine(lista1.Count);
//RETURN STANDYSP FUNCTION
double zwr(string myIndex)
{
var result = lista1.FirstOrDefault(lista1 => lista1.index == myIndex).standysp;
return result;
}
zwr("EMPIS_DESKA_FASOLKA");
//READ FROM TXT
string path = "C:/Users/Praktykant/Documents/textdocs/dok1.txt";
string plik = File.ReadAllText(path);
//Console.WriteLine(plik);
StreamReader objReader = new StreamReader(path);
myConnection.Close();
}
}
You mean something like this?
var list = File.ReadAllLines(path).Select(line =>
{
var tokens = line.Split("=");
var index = tokens[0];
var value = int.Parse(tokens[1]);
return new WynikPorownania
{
Indeks = index,
Ilosc = (int)Math.Max(value, zwr(index).standysp)
}
}).ToList();
(Depending on the size of the file, a StreamReader would be better than ReadAllLines)
You're almost there.
Extract text file line by line, and compute bigger value
StringReader r = new StringReader(plik);
string line;
while((line = r.ReadLine()) != null)
{
string index = line.Split('=')[0];
string textValue = line.Split('=')[1];
double biggerValue = Math.Max(
zwr(index),
double.Parse(textValue);
Console.WriteLine($"{index} > {biggerValue}");
}

how to optimize the time in executing the query in c# react

I am new to React and new to Web API. I am uploading data in a tabulator in react front end from the value that I am passing through the web API. I am passing value through the getReports function like this:
[HttpPost]
[Route("GetReports")]
public IHttpActionResult GetReports(string jwt, List<object> data)
{
if (!Common.VerificationToken.VerifyJWToken(jwt))
{
return null;
}
var to = data[0];
var from = data[1];
DateTime toDate = Convert.ToDateTime(to);
DateTime fromDate = Convert.ToDateTime(from);
var ReportData = db.T_CQL_COIL_DESC.Where(t => t.CCD_CREATED_ON >= toDate &&
t.CCD_CREATED_ON <= fromDate).ToList();
ReportsDTO dto = new ReportsDTO();
List<ReportsDTO> ReportDTO = new List<ReportsDTO>();
try
{
foreach (var report in ReportData)
{
List<vehicledetail> vehicle = new List<vehicledetail>();
var imgurl = "https://firebasestorage.googleapis.com/v0/b/tsl-coil-qlty-
monitoring-dev.appspot.com/";
dto = new ReportsDTO();
dto.Type = report.CCD_OP_TYPE;
dto.ID = report.CCD_COIL_ID;
vehicle = GetVehicleID(dto.ID);
vehicledetail vehicledetails = vehicle[0];
dto.vehicleno = vehicledetails.vehicleno.ToString();
dto.wagonno = vehicledetails.wagonno.ToString();
dto.Active = report.CCD_ACTIVE;
dto.ImgURL = report.CCD_IMAGE_URL != null ? imgurl + report.CCD_IMAGE_URL : "NA";
dto.Desc = report.CCD_VIEW_DESC != null ? report.CCD_VIEW_DESC : "NA";
ReportDTO.Add(dto);
}
return Ok(ReportDTO);
}
catch (Exception ex)
{
return Content(HttpStatusCode.NoContent, "Something went wrong");
}
}
The data in vehicledetail in vehicledetail vehicledetails = vehicle[0]; is getting populated from this function:
public List<vehicledetail> GetVehicleID(string coilID)
{
List<vehicledetail> vehicle = new List<vehicledetail>();
vehicledetail vehicledetails = new vehicledetail();
string oradb = Utilities.STAR_DB;
OracleConnection conn = new OracleConnection(oradb);
string query = "SELECT a.Vbeln, b.WAGON_NO FROM sapr3.lips a, sapr3.ZVTRRDA b WHERE
a.MANDT='600' AND a.CHARG='" + coilID + "' AND a.LFIMG > 0 AND a.MANDT = b.MANDT AND
a.VBELN = b.VBELN";
OracleDataAdapter da = new OracleDataAdapter(query, conn);
conn.Open();
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow row in dt.Rows)
{
vehicledetails.vehicleno = row["VBELN"].ToString();
vehicledetails.wagonno = row["WAGON_NO"].ToString();
}
conn.Close();
vehicle.Add(vehicledetails);
return (vehicle);
}
It is working fine but it is taking 30 seconds to load the below data:
How do I optimize this . Please help. Note: that it is taking 30 seconds to upload this data
Few other things aside, the major problem seems to be that you are querying database for each vehicle.
In this particular scenario it might very well be better to select all vehicle ids and query them all.
var vehicleIds = reportData.SelectMany(t => t.ID);
You can then form a query that will get all vehicle details together. This will reduce the number of database calls and it can have massive impact on time.
Another thing to check is if there's any index created on the vehicle id column in database as that may also help speed things up.

Overwriting of variable in SqlDataReader while-loop

I have read some threads that seem to be similar to this but can't find the fix for my issue, I've not used stack overflow much so pls bear with me
I have a while loop using an SqlDataReader which is pulling information from a DB and putting it into a List for Development Requests as below
public ListOfDevelopmentRequestsModel GetDevRequests(List<SelectListItem> evaluators)
{
SqlCommand cmd = new SqlCommand(StoredProcedures.DevRequests.GetDevRequests, Conn);
cmd.CommandType = CommandType.StoredProcedure;
ListOfDevelopmentRequestsModel ListOfDevRequests = new ListOfDevelopmentRequestsModel();
Conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
DateTime requestDate = Convert.ToDateTime(reader["DateCreated"].ToString());
string requestorFirstName = reader["Staff First Name"].ToString();
string requestorLastName = reader["Staff Last Name"].ToString();
string requestorEmailAddress = reader["Staff Email"].ToString();
string solutionName = reader["SolutionName"].ToString();
string solutionDescription = reader["SoultionDescription"].ToString();
string solutionElementName = reader["SolutionElementName"].ToString();
string solutionElementDescription = reader["SolutionElementDescription"].ToString();
string itemToChange = reader["ItemChange"].ToString();
string changeDetails = reader["ChangeDetail"].ToString();
List<SelectListItem> evaluatorList = new List<SelectListItem>(DisplayCurrentEvaluator(evaluators, evaluator));
DevelopmentRequestModel DevRequest = new DevelopmentRequestModel
{
RequestDate = requestDate,
RequestorName = $"{requestorFirstName} {requestorLastName}",
RequestorEmailAddress = requestorEmailAddress,
SolutionName = solutionName,
SolutionDescription = solutionDescription,
SolutionElementName = solutionElementName,
SolutionElementDescription = solutionElementDescription,
ItemToChange = itemToChange,
ChangeDetails = changeDetails,
AccordionHeading = $"{(changeID.PadLeft(4, '0'))} - {requestorFirstName} {requestorLastName} - {itemToChange}"
};
ListOfDevRequests.DevelopmentRequests.Add(DevRequest);
}
Conn.Close();
return ListOfDevRequests;
}
I also have a List for getting Evaluators of the requests
public static List<SelectListItem> GetEvaluators()
{
List<SelectListItem> evaluators = new List<SelectListItem>();
SqlCommand cmd = new SqlCommand(StoredProcedures.DevRequests.GetEvaluators, Conn);
cmd.CommandType = CommandType.StoredProcedure;
Conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
evaluators.Add(
new SelectListItem
{
Text = reader["Staff Name"].ToString(),
Value = reader["Staff Code"].ToString(),
});
}
Conn.Close();
return evaluators;
}
Finally I have a List that will pass the above Evaluators List in and the Evaluator that was pulled from the DB: string evaluator = reader["Evaluator"].ToString(); and will set the default value of the select list based on whether the Evaluator name matches the Text value, and set it as the selected select list item.
public List<SelectListItem> DisplayCurrentEvaluator(List<SelectListItem> evaluators, string evaluator)
{
foreach (var item in evaluators)
{
if (item.Text == evaluator)
{
item.Selected = true;
}
else
{
item.Selected = false;
}
}
return evaluators;
}
The issue is that the first item in the loop has the Evaluator "Bill" and "Bill" is selected, and works fine, however the second item in the loop is "John", and when it sets "John" to selected, it replaces "Bill" as the selected value in the first item with "John"
The code has ended up a mess as I have tried multiple different ways to fix but I'm stumped and would appreciate help.
Sorry if the post is formatted poorly to read, I can try to reformat and provide more information if requested.
Cheers
EDITED CODE:
GetDevRequests()
public ListOfDevelopmentRequestsModel GetDevRequests(List<SelectListItem> evaluators)
{
SqlCommand cmd = new SqlCommand(StoredProcedures.DevRequests.GetDevRequests, Conn);
cmd.CommandType = CommandType.StoredProcedure;
ListOfDevelopmentRequestsModel ListOfDevRequests = new ListOfDevelopmentRequestsModel();
Conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
List<SelectListItem> evaluatorList = new List<SelectListItem>();
while (reader.Read())
{
string changeID = reader["ChangeID"].ToString();
string evaluator = reader["Evaluator"].ToString();
string status = reader["Status"].ToString();
string priority = reader["Priority"].ToString();
string eliteID = reader["RequestorID"].ToString();
DateTime requestDate = Convert.ToDateTime(reader["DateCreated"].ToString());
string requestorFirstName = reader["Staff First Name"].ToString();
string requestorLastName = reader["Staff Last Name"].ToString();
string requestorEmailAddress = reader["Staff Email"].ToString();
string solutionName = reader["SolutionName"].ToString();
string solutionDescription = reader["SoultionDescription"].ToString();
string solutionElementName = reader["SolutionElementName"].ToString();
string solutionElementDescription = reader["SolutionElementDescription"].ToString();
string itemToChange = reader["ItemChange"].ToString();
string changeDetails = reader["ChangeDetail"].ToString();
evaluatorList = DisplayCurrentEvaluator(evaluators, evaluator);
DevelopmentRequestModel DevRequest = new DevelopmentRequestModel
{
ChangeID = (changeID.PadLeft(4, '0')),
Evaluator = evaluator,
Evaluators = evaluatorList,
Status = status,
Priority = priority,
EliteID = eliteID,
RequestDate = requestDate,
RequestorName = $"{requestorFirstName} {requestorLastName}",
RequestorEmailAddress = requestorEmailAddress,
SolutionName = solutionName,
SolutionDescription = solutionDescription,
SolutionElementName = solutionElementName,
SolutionElementDescription = solutionElementDescription,
ItemToChange = itemToChange,
ChangeDetails = changeDetails,
AccordionHeading = $"{(changeID.PadLeft(4, '0'))} - {requestorFirstName} {requestorLastName} - {itemToChange}"
};
ListOfDevRequests.DevelopmentRequests.Add(DevRequest);
}
Conn.Close();
return ListOfDevRequests;
}
DisplayCurrentEvaluator()
public List<SelectListItem> DisplayCurrentEvaluator(List<SelectListItem> selectListItems, string selectListDefaultItem)
{
foreach (var item in selectListItems)
{
item.Selected = item.Text == selectListDefaultItem;
}
return selectListItems;
}
The problem is in this line:
List<SelectListItem> evaluatorList = new List<SelectListItem>(DisplayCurrentEvaluator(evaluators, evaluator));
First, this can also be written as
List<SelectListItem> evaluatorList = DisplayCurrentEvaluator(evaluators, evaluator);
Your DisplayCurrentEvaluator already returns a correct list, so there is no need to copy it into a new one.
But this is a minor point as you don't use that evaluatorList as far as I can see. In every iteration of that while-loop you are creating a new one (which probably isn't what you want) and then you forget about it. I also don't see where evaluator is set, but that is probably in code you didn't show.
So you will need to generate this list once, outside the loop and keep it (probably in a class-level field or property).
And an extra tip, that DisplayCurrentEvaluator method can also be written as
public List<SelectListItem> DisplayCurrentEvaluator(List<SelectListItem> evaluators, string evaluator)
{
foreach (var item in evaluators)
{
item.Selected = item.Text == evaluator;
}
return evaluators;
}
EDIT after code was shown that set evaluator and used the resulting evaluatorList
Your DisplayCurrentEvaluator updates the original evaluators list and returns it. This effectively results in every evaluatorList pointing to the same list, where the last update wins. So make sure you return a new list.
public List<SelectListItem> DisplayCurrentEvaluator(List<SelectListItem> evaluators, string evaluator)
{
var result = new List<SelectListItem>(evaluators.Count);
foreach (var item in evaluators)
{
result.Add(new SelectListItem { Text = item.Text, Value = item.Value, Selected= item.Text == evaluator};
}
return result;
}
Additionally, declare the evaluatorList (only) inside of the loop.
var evaluatorList = DisplayCurrentEvaluator(evaluators, evaluator);

Sql where statement not working using asp.net?

To better explain my problem with my personal website project, I would start off with the database that I have created. The table is called guitarItems.
This table is where i get data for displaying images and guitar details in the webpage. In order to do this, I created a method named "GetGuitarItems" to execute and read the sql statements.
public static ArrayList GetGuitarItems(string itemCategory)
{
ArrayList list = new ArrayList();
string query = string.Format("SELECT * FROM guitarItems WHERE brand LIKE '{0}'", itemCategory);
try
{
conn1.Open();
command1.CommandText = query;
SqlDataReader reader = command1.ExecuteReader();
while (reader.Read())
{
int id = reader.GetInt32(0);
string type = reader.GetString(1);
string brand = reader.GetString(2);
string model = reader.GetString(3);
double price = reader.GetDouble(4);
string itemimage1 = reader.GetString(5);
string itemimage2 = reader.GetString(6);
string description = reader.GetString(7);
string necktype = reader.GetString(8);
string body = reader.GetString(9);
string fretboard = reader.GetString(10);
string fret = reader.GetString(11);
string bridge = reader.GetString(12);
string neckpickup = reader.GetString(13);
string bridgepickup = reader.GetString(14);
string hardwarecolor = reader.GetString(15);
GuitarItems gItems = new GuitarItems(id, type, brand, model, price, itemimage1, itemimage2, description, necktype, body,
fretboard, fret, bridge, neckpickup, bridgepickup, hardwarecolor);
list.Add(gItems);
}
}
finally
{
conn1.Close();
}
return list;
}
Next part is this code where you display the data that you have retrieved from the database.
public partial class Pages_GuitarItems1 : System.Web.UI.Page
{
private string brandType = "Ibanez";
private int x = 0;
protected void Page_Load(object sender, EventArgs e)
{
FillPage();
}
private void FillPage()
{
ArrayList itemList = new ArrayList();
ArrayList itemListPage = new ArrayList();
if (!IsPostBack)
{
itemList = ConnectionClassGuitarItems.GetGuitarItems("%");
}
else
{
itemList = ConnectionClassGuitarItems.GetGuitarItems(brandType);
}
StringBuilder sb = new StringBuilder();
foreach (GuitarItems gList in itemList)
{
itemListPage.Add("GuitarItemsIbanezDetails" + (x + 1) + ".aspx");
sb.Append(
string.Format(
#"
<div class='one-two'>
<a href='{3}' runat='server'><img runat='server' src='{0}'/></a>
<div class='content'>
<div id='label'>{1} {2}</div>
</div>
</div>", gList.ItemImage1, gList.Brand, gList.Model, itemListPage[x]));
x++;
}
lblOutput.Text = sb.ToString();
}
}
Now the problem is its displaying every guitar items in the database. As shown from the code above, what I'm trying to display is only the guitar items with brand "Ibanez" in it. I have my suspicions with the foreach code but atleast for now, the GetGuitarItemsMethod is designed to get only the Ibanez guitar items and the data will be passed on to the ArrayList itemList variable for displaying. And I have also checked the sql statement and it seems correct. Hope you guys can help me on this one.
Change from
if (!IsPostBack)
{
itemList = ConnectionClassGuitarItems.GetGuitarItems("%");
}
else
{
itemList = ConnectionClassGuitarItems.GetGuitarItems(brandType);
}
to
itemList = ConnectionClassGuitarItems.GetGuitarItems(brandType);

How to use iTextSharp to populate radio button

I have a table and one of the column is YesNo which is of type varchar(3). I have two radio buttons in my PDF file which is in an array:
pg1rb (radio group field)
--> c1 (radio button one (yes))
--> c2 (radio button two (no))
I set textboxes like this in my code:
formFieldMap["topmostSubform[0].Page1[0].f1_01_0_[0]"] = reader.GetValue(0).ToString();
How can I select YES or NO radio button based on the row value?
Can I do something like this:
formFieldMap["pg1rb"] = reader.GetBoolean(10); //10 is the 9th column which is Yes/No value
Or do I get the value and based on it select the radio button, something like this:
if (reader.GetValue(10).ToString() == "Yes") {
formFieldMap["pg1rb"][c1] = "1";
else {
formFieldMap["pg1rb"][c2] = "1";
}
My SQL table:
I am trying to follow this site: Website example
My function that actually does the conversion:
public void writeData(string k, string c)
{
Conn = new SqlConnection(cString);
Conn.Open();
//MessageBox.Show(k);
//MessageBox.Show(c);
var pdfPath = Path.Combine(Server.MapPath("~/PDFTemplates/forme.pdf"));
// Get the form fields for this PDF and fill them in!
var formFieldMap = PDFHelper.GetFormFieldNames(pdfPath);
//if more than multiple entries, verify by name and the last four ssn
sqlCode = "SELECT * FROM [DSPCONTENT01].[dbo].[TablePDFTest] WHERE [name] = '" + k + "' AND [ssn3] = " + c + "";
//sqlCode = "SELECT * FROM [DSPCONTENT01].[dbo].[TablePDFTest] WHERE [name] = #name2 AND [ssn3] = #ssnnum";
//MessageBox.Show("" + sqlCode.ToString());
using (SqlCommand command = new SqlCommand(sqlCode, Conn))
{
command.CommandType = CommandType.Text;
//command.Parameters.AddWithValue("name2", k);
//command.Parameters.AddWithValue("ssnnum", c);
using (reader = command.ExecuteReader())
{
if (reader.HasRows)
{
if (reader.Read())
{
//MessageBox.Show(reader.GetValue(0).ToString());
/*formFieldMap["topmostSubform[0].Page1[0].f1_01_0_[0]"] = reader.GetValue(0).ToString();
formFieldMap["topmostSubform[0].Page1[0].f1_02_0_[0]"] = reader.GetValue(1).ToString();
formFieldMap["topmostSubform[0].Page1[0].f1_04_0_[0]"] = reader.GetValue(2).ToString();
formFieldMap["topmostSubform[0].Page1[0].f1_05_0_[0]"] = reader.GetValue(3).ToString();
formFieldMap["topmostSubform[0].Page1[0].f1_07_0_[0]"] = reader.GetValue(4).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField1[0]"] = reader.GetValue(5).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[0]"] = reader.GetValue(6).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[1]"] = reader.GetValue(7).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[2]"] = reader.GetValue(8).ToString();
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[3]"] = reader.GetValue(9).ToString();*/
if (reader.GetValue(10).ToString() == "Yes")
{
//MessageBox.Show("YES");
}
else if (reader.GetValue(10).ToString() == "No")
{
//MessageBox.Show("NO");
}
}
}
}
}
// Requester's name and address (hard-coded)
formFieldMap["topmostSubform[0].Page1[0].f1_06_0_[0]"] = "Medical Group\n12 Westchester Ave\nPurchase, NY 10121";
var pdfContents = PDFHelper.GeneratePDF(pdfPath, formFieldMap);
PDFHelper.ReturnPDF(pdfContents, "Completed-W9.pdf");
}
The PDFHelper class:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.IO;
using iTextSharp.text.pdf;
public class PDFHelper
{
public static Dictionary<string, string> GetFormFieldNames(string pdfPath)
{
var fields = new Dictionary<string, string>();
var reader = new PdfReader(pdfPath);
foreach (DictionaryEntry entry in reader.AcroFields.Fields)
fields.Add(entry.Key.ToString(), string.Empty);
reader.Close();
return fields;
}
public static byte[] GeneratePDF(string pdfPath, Dictionary<string, string> formFieldMap)
{
var output = new MemoryStream();
var reader = new PdfReader(pdfPath);
var stamper = new PdfStamper(reader, output);
var formFields = stamper.AcroFields;
foreach (var fieldName in formFieldMap.Keys)
formFields.SetField(fieldName, formFieldMap[fieldName]);
stamper.FormFlattening = false;
stamper.Close();
reader.Close();
return output.ToArray();
}
// See http://stackoverflow.com/questions/4491156/get-the-export-value-of-a-checkbox-using-itextsharp/
public static string GetExportValue(AcroFields.Item item)
{
var valueDict = item.GetValue(0);
var appearanceDict = valueDict.GetAsDict(PdfName.AP);
if (appearanceDict != null)
{
var normalAppearances = appearanceDict.GetAsDict(PdfName.N);
// /D is for the "down" appearances.
// if there are normal appearances, one key will be "Off", and the other
// will be the export value... there should only be two.
if (normalAppearances != null)
{
foreach (var curKey in normalAppearances.Keys)
if (!PdfName.OFF.Equals(curKey))
return curKey.ToString().Substring(1); // string will have a leading '/' character, so remove it!
}
}
// if that doesn't work, there might be an /AS key, whose value is a name with
// the export value, again with a leading '/', so remove it!
var curVal = valueDict.GetAsName(PdfName.AS);
if (curVal != null)
return curVal.ToString().Substring(1);
else
return string.Empty;
}
public static void ReturnPDF(byte[] contents)
{
ReturnPDF(contents, null);
}
public static void ReturnPDF(byte[] contents, string attachmentFilename)
{
var response = HttpContext.Current.Response;
if (!string.IsNullOrEmpty(attachmentFilename))
response.AddHeader("Content-Disposition", "attachment; filename=" + attachmentFilename);
response.ContentType = "application/pdf";
response.BinaryWrite(contents);
response.End();
}
}
Your question was confusing because it used a reader object that didn't refer to iTextSharp's PdfReader class and it used a formFieldMap object of which the type was unknown (it doesn't seem related to iTextSharp). Your edit was very welcome to understand the question.
The field names you mention look as if they are fields in an XFA form, but the article you refer to talks about filling out AcroForm documents, so let's assume that your form was indeed born as an XFA form, but later on converted to an AcroForm.
In this case, nobody will be able to tell you which values to pick to set the radio buttons without seeing the PDF. Please download chapter 6 of my book and read section 6.3.5, more specifically where it says Inspecting the form and its fields. On page 183, you can read that the possible values for a group of radio buttons is either "Off"–no radio button is selected— or a code that is defined in the form itself.
For instance: in the example from the book, the possible values for the category group were spec, toro, anim, etc...
This means that you can set a radio box in that group like this:
formFields.SetField("category", "spec");
or:
formFields..SetField("category", "toro");
or:
formFields.SetField("category", "anim");
and so on.
So, if you want to set a radio button in a radiogroup named pg1rb, you first need to know which are the possible values. You assume that the possible values are "Yes" and "No" in which case you could use:
formFields.SetField("pg1rb", "Yes");
or
formFields.SetField("pg1rb", "No");
But the possible values could also be "1" and "0", "On" and "Off", "true" and "false",... The possible values were chosen by the person who created the form.
You can get these values programmatically by using the code from page 182:
StringBuilder sb = new StringBuilder();
sb.Append("Possible values for pg1rb:");
sb.Append(Environment.NewLine);
states = form.GetAppearanceStates("pg1rb");
for (int i = 0; i < states.Length - 1; i++) {
sb.Append(states[i]);
sb.Append(", ");
}
sb.Append(states[states.Length - 1]);
Inspect what was written to the sb object and you have the values you are looking for.

Categories