I am working on .net platform. I have created a word template(.dotx) and added mergefields in it. i am replacing merge field from database column values. Now i want to loop on merge field.
for example :- i have merge fields named < DepartmentID > and < DepartmentName > . And i am getting data from database's table named "tblDepartment" which have two columns "DepID" and "DepName". this table have 5 rows. i want to loop on these mergefields.
i want to show file like this.
before execute the docx file is :-
< DepartmentID > < DepartmentName >
after code execute:-
DepID DepName
1 DotNet
2 Java
3 PHP
Here Is My Code:
foreach (Word.Field myMergeField in wordDoc.Fields)
{
Word.Range rngFieldCode = myMergeField.Code;
String fieldText = rngFieldCode.Text;
// ONLY GETTING THE MAILMERGE FIELDS
if (fieldText.StartsWith(" MERGEFIELD"))
{
Int32 endMerge = fieldText.IndexOf("\\");
Int32 fieldNameLength = fieldText.Length - endMerge;
String fieldName = fieldText.Substring(11, endMerge - 11);
fieldName = fieldName.Trim().Replace("\"", "");
if (fieldName == "DepartmentID")
{
myMergeField.Select();
wordApp.Selection.TypeText("DepartmentID");
}
if (fieldName == "DepartmentName")
{
EAccreditationEntities dbModel = new EAccreditationEntities();
var q = (from p in dbModel.Departments select p).ToList();
//here q has all data from database , have columns (ID and Name of Department)
myMergeField.Select();
wordApp.Selection.TypeText("DEPNAME");
}
}
And the problem is that , my document have five pages , merge fields on 5th page and sql query returns 5 rows. when i am executing my code ,it shows first record on 5th page, then 6,7,8,9 pages create with 1,2,3,4 pages content and on 10th page shows 2nd record and so on.... Whole process creates 25 pages document file.
But i want to show all data on 5th page only. and not want to create extra pages.
Related
I have a View with a data source of the shipment table. This view has a method that contains a query. This query takes a shipment id and returns the sales id from the sales line table for this shipment. This view has a computed field that is the output of the query. The computed field is then used on a form.
If I hard code the shipment id the process works correctly. My question is how do I get the shipment id dynamically from a list of shipment ids. For instance, I have a form that lists all shipments. I want to place a field next to the shipment id that contains the calculated sales id from the process above.
Bottom line: I want the first column of a grid to be a shipment id and the second column to be the sales id for the shipment in the first column.
This is an example of the method described above that contains the query:
private static server str findSalesLine()
{
WMSShipment wmsShipment;
WMSOrderTrans wmsOrderTrans;
SalesLine salesLine;
select wmsShipment
join wmsOrderTrans
where wmsShipment.shipmentId == '1040383'
&& wmsShipment.shipmentId == wmsOrderTrans.shipmentId
join salesId from salesLine
where salesLine.LineNum == wmsOrderTrans.inventTransRefLineNum
&& salesLine.SalesID == wmsOrderTrans.inventTransRefID
&& salesLine.ExternalItemId != '';
return salesLine.SalesId;
}
I would use a computed column similar to the below. I'm in a different environment than you so the SQL is not valid on my box but it should work on yours.
Add a new string computed column to your view, then set this method as the datamethod.
public static server str getSalesId()
{
tableName viewName = tableStr(testView);//name of your view
DataSourceName wmsShipmentDsName = identifierStr(WMSShipment);//change if your dsname is different on your view
str returnStr;
returnStr =
" SELECT G1.SALESID FROM SALESLINE G1 " + //don't use "T1 T2" etc as aliases on computed columns
" JOIN WMSORDERTRANS G2 ON " +
" G1.LINENUM = G2.INVENTTRANSREFLINENUM AND " +
" G1.SALESID = G2.INVENTTRANSREFID AND " +
" SALESLINE.EXTERNALITEMID <> '' " +
" WHERE G2.SHIPMENTID == " +
SysComputedColumn::returnField(viewName, wmsShipmentDsName, fieldStr(WMSShipment, ShipmentId));
return returnStr;
}
I think what you're looking for is a query range (https://msdn.microsoft.com/en-us/library/aa638454.aspx) or a display method (https://msdn.microsoft.com/en-us/library/aa595058.aspx)
Do you have any more detail or sample code?
I have created a temporary datatable to store temporary data before send it to database. But after creating that now i want to fetch all the rows from this temporary datatable and save them to data base. For this i loop my datatable using foreach loop
foreach(DataRow r in dt.Rows)
{
string Fname = dt.Rows[0]["Name"].ToString();
string cType = dt.Rows[0]["ContentType"].ToString();
byte[] ePic = (byte[])dt.Rows[0]["pic"];
BAL.saveEventPictures(Convert.ToInt32(lblEventID.Text), Fname, cType, ePic);
}
The problem is that it only fetch the data of first row again and again for the whole loop count. Like if I have 4 datarows with different information, then this will store the data of 1st row in the database for 4 times. What mistake am i doing?
dt.Rows[0] means you are always accessing the first row of your DataTable.You need to use a for loop instead of a foreach and use i to access each index of your table:
for (int i = 0; i < dt.Rows.Count; i++)
{
string Fname = dt.Rows[i]["Name"].ToString();
string cType = dt.Rows[i]["ContentType"].ToString();
byte[] ePic = (byte[])dt.Rows[i]["pic"];
BAL.saveEventPictures(Convert.ToInt32(lblEventID.Text), Fname, cType, ePic);
}
You can use for loop to fetch all value regarding their columns in datatable to assign value in their variables so you can use this way. Because if you use hard coded index of datatable rows then it should fetch only single data every time.
Here i is index of rows and column name to get value from rows. So use dynamically based indexing use for get all records.
for (int i = 0; i < dt.Rows.Count; i++)
{
string Fname = dt.Rows[i]["Name"].ToString();
string cType = dt.Rows[i]["ContentType"].ToString();
byte[] ePic = (byte[])dt.Rows[i]["pic"];
BAL.saveEventPictures(Convert.ToInt32(lblEventID.Text), Fname, cType, ePic);
}
I'm trying to use a form to gather data and store them in a table and immediately do some calculations on that data and store the results in a separate table..
But I don't seem to be able to read the first table immediately after insertion..
I always encounter a zero in my calculation meaning that the first table is considered empty when trying to calculate (but is not empty when the page is refreshed, meaning that the data finally finds its way to the first table anyway) ..
This is the example:
#{
// this is the code that gathers data from a form and stores the data in a table
foreach(var row in db.Query(selectquestions))
{
var questionid = row.QuestionId;
var answer = Request["Q" + row.QuestionId.ToString()];
var insertanswers = "INSERT into Answers (UserId,QuestionId,Answer,ExamId) VALUES(#0, #1, #2, #3)";
db.Execute(insertanswers,userid,questionid,answer,1);
}
// this is the code that tries to immediately use the data stored by the above statement and store the new calculation results in a separate table
int totalquestions= db.Query( some query using the first table ).Count();
int correctanswers= db.Query( some query using the first table ).Count();
int incorrectanswers=db.Query( some query using the first table ).Count();
var score= (float)(correctanswers * 3 - incorrectanswers) / (totalquestions * 3)*100;
var insertscores = "INSERT into Scores (UserId,ExamId,ItemId,Score) VALUES(#0, #1, #2, #3)";
db.Execute(insertscores,userid,1,1,score.ToString());
}
I'm using web pages/razor/SQL Server CE .. any advice would be appreciated
I have a Database table:
Item
ID (uniqueidentifier)
Index (int)
I have a list of 2000 key-value pairs items where the key is ID and value is Index, which i need to update it. How can i update all the 2000 items from database using one single sql query?
Right now i have something like this:
// this dictionary has 2000 values
Dictionary<Guid, int> values = new Dictionary<Guid,int>();
foreach(KeyValuePair<Guid, int> item in values)
{
_db.Database.ExecuteSqlCommand("UPDATE [Item] SET [Index] = #p0 WHERE [Id] = #p1", item.Value, item.Key);
}
However, i am making too many requests to the SQL Server, and i want to improve this.
Use table value parameters to send those values to SQL Server and update Items table in one shot:
CREATE TYPE KeyValueType AS TABLE
(
[Key] GUID,
[Value] INT
);
CREATE PROCEDURE dbo.usp_UpdateItems
#pairs KeyValueType READONLY
AS
BEGIN
UPDATE I
SET [Index] = P.Value
FROM
[Item] I
INNER JOIN #pairs P ON P.Id = I.Id
END;
GO
If you really need to update in that manner and have no other alternative - the main way around it could be this rather "ugly" technique (and therefore rarely used, but still works pretty well);
Make all 2000 statements in one string, and execute that one string. That makes one call to the database with the 2000 updates in it.
So basically something like this (code not made to actually run, it's an example so t
Dictionary<Guid, int> values = new Dictionary<Guid, int>();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (KeyValuePair<Guid, int> item in values)
{
sb.Append(String.Format("UPDATE [Item] SET [Index] = {0} WHERE [Id] = '{1}';", item.Value, item.Key));
}
_db.Database.ExecuteSqlCommand(sb.ToString);
How to insert and retrive multiple asp.net checkboxes values to MSSQl database as comma seperaed string 1,2,3,4,5 using vb.net ?
and retrieve the inserted checkbox chekched in disabled form ..using vb.net
example of this is :
http://www.redbus.in/Booking/SeatSelection.aspx?rt=4017230&doj=31-Dec-2010&dep=04:55%20PM&showSpInst=false
I want this type of whole layout in vb.net ... means if user registered selected seats then then next the same page load for todays date the selected seats will be disabled ...
pleas provide me the code snippet for that // insert and retrieve funda... in checkbox
Try with such a loop
string str = "";
for (int i = 0; i <= 29; i++)
{
if (CheckBoxList1.Items[i].Selected)
{
string b = CheckBoxList1.Items[i].Value;
str += b + " , ";
}
}
than make an insert statement and you are putting all the checkbox values into a column.
than just call select statement call the column
You are doing a very bad thing storing lists of values in a single MSSQL column. I know it may be convenient now, but it is always eventually bad news. Why not store booked seats in their own table, one seat per row? When you store a list of values in a column, you restrict access to the information stored in that column to only the code that can split the list. It isn't available to database queries or to other code as a list, merely as a string. You will end up replicating the code to split this string to other places that need the list data.