Pass value in Crystal report - crystal-reports

I add formula field region,fromdate,todate in report
i.e.
UPDATED IMAGE
Also I try this another method:
protected void Report_Click(object sender, EventArgs e)
{
data crystalReport = new data();
crystalReport.DataDefinition.FormulaFields["region"].Text = regiondrop.SelectedValue;
crystalReport.DataDefinition.FormulaFields["fromdate"].Text = fromdate.Value;
crystalReport.DataDefinition.FormulaFields["todate"].Text = todate.Value;
BindReport(crystalReport,Convert.ToDateTime(fromdate.Value), Convert.ToDateTime(todate.Value), regiondrop.SelectedValue);
}
This show error on page:
Error
This field name is not known. Details: errorKind Error in File temp_2c6994eb-49ef-432f-bfd7-af0eb80dc7ec 4032_6896_{5E54477E-F078-41DF-BD52-AF042B96DA53}.rpt: Error in formula fromdate: '{DataTable1.StartDate}' This field name is not known. Details: errorKind
Now this is working finally with the help of #Furtiro
public void BindReport(ReportDocument crystalReport, DateTime fromdate, DateTime todate, string region)
{
T1 t = new T1();
DateTime fdate = new DateTime(fromdate.Year, fromdate.Month, fromdate.Day, 0, 0, 0);
DateTime tdate = new DateTime(todate.Year, todate.Month, todate.Day, 23, 59, 59);
List<griddataresult_Result> dsc = t.griddataresult(fdate, tdate, region).ToList();
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("OwnerName", typeof(string));
dt.Columns.Add("RegNo", typeof(string));
foreach (var c in dsc)
{
dt.Rows.Add(c.ID, c.OwnerName, c.RegNo, c.total_voilatio, c.MileageAccumlation, c.MaxSpeed);
}
crystalReport.DataDefinition.FormulaFields["region"].Text = "'" + region + "'";
crystalReport.DataDefinition.FormulaFields["fromdate"].Text = "'" + fromdate + "'";
crystalReport.DataDefinition.FormulaFields["todate"].Text = "'" + todate + "'";
crystalReport.SetDataSource(dt);
CrystalReportViewer1.ReportSource = crystalReport;
CrystalReportViewer1.DataBind();
}

You can instanciate your report like an object , replace your line :
ReportDocument crystalReport = new ReportDocument();
By :
data crystalReport = new data();
Here data is the name of you .rpt class.
*Update *
You don't understand that ReportDocument is an object, your object here will be your data class.
So all the lines when you set doc = crystalreport are useless because you don't work on your crystalReport object but on other objects.
Second update :
I didn't see your access to the formula, you're not supposed to write the "#' in the name of your formula. My bad sorry , here's your working code :
protected void Report_Click(object sender, EventArgs e)
{
data crystalReport = new data();
crystalReport.DataDefinition.FormulaFields["region"].Text = "'" + regiondrop.SelectedValue.ToString() + "'";
crystalReport.DataDefinition.FormulaFields["fromdate"].Text = "'" + fromdate.Value.ToString() +"'";
crystalReport.DataDefinition.FormulaFields["todate"].Text = "'"+ todate.Value.ToString() + "'";
BindReport(crystalReport,Convert.ToDateTime(fromdate.Value), Convert.ToDateTime(todate.Value), regiondrop.SelectedValue);
}
Be careful about the dataType and parse when you write a formula in c# code, for example if you want to display some text in a formula dynamically you'll need to cast your data with quotes
Like report.DataDefinition.FormulaFields["yourformula"].Text ="'Hello world'";
Dont forget the quotes, simple or double quotes will works.
Best regards,

Related

Conversion failed when converting the varchar value to data type

i search a lot but didn't find what i want this question is ask by many users here but i didn't find my solution so i ask this question.
i have page in which i have Assign and withdraw button which
is used to Assign and withdraw device id for the selected group
id (group id fetch from dropdownlist) from one list-box to another
that part is completed
Now when i add another device id for the same group id i need to
append that updated record and show it in listbox2.
here is my code:
string queryString1 = "select device_id from device_group_master where group_id='" + ddlGroupName.SelectedValue.ToString() +"'";
SqlDataAdapter newdataAdapter = new SqlDataAdapter(queryString1, con);
SqlCommandBuilder newcommandBuilder = new SqlCommandBuilder(newdataAdapter);
newdataAdapter.Fill(ds1, "table");
if (ds1.Tables["table"].Rows.Count != 0)
{
if (ds1.Tables["table"].Rows[0][0].ToString() == "0")
{
string queryString2 = "update DEVICE_GROUP_MASTER set DEVICE_ID='" + device.ToString() + "', NOT_EXCLUDE_DEVICE_ID='" + enable + "' where GROUP_ID='" + ddlGroupName.SelectedValue.ToString() + "'";
SqlCommand update = new SqlCommand(queryString2, con);
update.CommandType = CommandType.Text;
update.ExecuteNonQuery();
}
else
{
string append;
append = ds1.Tables["table"].Rows[0][0].ToString();
append += ","+ device;
string queryString2 = "update DEVICE_GROUP_MASTER set DEVICE_ID='" + append.ToString() + "' where GROUP_ID='" + ddlGroupName.SelectedValue.ToString() + "'";
SqlCommand update = new SqlCommand(queryString2, con);
update.CommandType = CommandType.Text;
update.ExecuteNonQuery();
}
}

Populating unbound field in crystal report

I have a crystal report with these fields:
-Name
-Other
The field 'Other' is not a database field, so I added it as an unbound field.
Then I have this code in my controller:
DataSet ds = new DataSet();
DataTable dt = new DataTable("Product");
dt.Columns.Add("Name");
dt.Columns.Add("Other");
When I have populated the above datatable I add it to the dataset, anf then set the dataset as report's datasource:
ReportDocument report = new ReportDocument();
string reportFile = Server.MapPath("~/") + "\\bin\\Reports\\MyReport.rpt";
report.Load(reportFile);
report.SetDataSource(ds);
Then I set the export options (it's a excel report).
In my report I'm getting the text for the 'Name' field correctly, but the 'Other' field is empty. How can I associate the column from the datatable to this field?
Thanks in advance.
This is aspx File :
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" EnableParameterPrompt="false"
ReuseParameterValuesOnRefresh="true" EnableDatabaseLogonPrompt="False" ToolPanelView="None"
HasToggleParameterPanelButton="false" HasCrystalLogo="False" />
This is Cs File ......
protected void btnSubmit_Click(object sender, EventArgs e)
{
LoadData();
}
protected void LoadData()
{
DataSet ds= null;
ds = new DataSet();
DataTable dt = new DataTable("Product");
dt.Columns.Add("Name");
dt.Columns.Add("Other");
rptDoc.Load(Server.MapPath("~/bin/Reports/MyReport.rpt"));
rptDoc.SetDataSource(ds);
CrystalReportViewer1.ReportSource = rptDoc;
CrystalReportViewer1.DataBind();
CrystalReportViewer1.refreshreport();
}
Try this code.......
try this with VB
'pass texbox2 to unbounddate1
CrystalReportSource1.ReportDocument.DataDefinition.FormulaFields.Item("unbounddate1").Text = "'" & Me.TextBox2.Text & "'"
'pass texbox3 to unbounddate2 CrystalReportSource1.ReportDocument.DataDefinition.FormulaFields.Item("unbounddate2").Text = "'" & Me.TextBox3.Text & "'"

How to filter datagridview using text inputted from a rich text box?

I have a datagridview that I want to display a data from a database. But I don't want it to display all of the data. I want it to display the data for a specific ID only. Meaning if the user enters 3 ID, it will display the info for that 3 ID. Hence I want to use a rich text box as a filter so that the user can enter multiple ID for each line in the rich text box. The user can enter the ID No. within the rich text box and the data will be used as a filter to display the data for that particular ID. But I cannot make it read beyond the first line of the rich text box. If I enter just one ID in the first line, it works perfectly, but if I enter a second ID in the second line, or in the third line, then it will not display anything at all. I tried using for loop to read each line of the rich text box but it doesn't work. Any advice or solution??
here is my code :
namespace TrackCon
{
public partial class trackInput : Form
{
public trackInput()
{
InitializeComponent();
}
/*private void trackInput_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'trackingBMSDATADataSet.BRDATA' table. You can move, or remove it, as needed.
this.bRDATATableAdapter.Fill(this.trackingBMSDATADataSet.BRDATA);
}*/
private void trackBtn_Click(object sender, EventArgs e)
{
RichTextBox dynamicRichTextBox = new RichTextBox();
DataTable dt = null;
string connoInput = richTextBox1.Text;
string conString = Properties.Settings.Default.BMSDATAConnectionString;
//string[] RichTextBoxLines = dynamicRichTextBox.Lines;
foreach (char line in richTextBox1.Text)
{
using (SqlCeConnection con = new SqlCeConnection(#"Data Source=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2008\Projects\TrackCon\TrackCon\BMSDATA.sdf;Persist Security Info = True;Password=xxxx"))
{
con.Open();
SqlCeCommand com = new SqlCeCommand("SELECT conno,cmpsno,ctrx,dsysdate,cstnno,corigin FROM BRDATA WHERE conno = '" + richTextBox1.Text + "'OR cmpsno = '" + richTextBox1.Text + "'", con);
SqlCeDataAdapter adap = new SqlCeDataAdapter(com);
DataSet set = new DataSet();
adap.Fill(set);
if (set.Tables.Count > 0)
{
dt = set.Tables[0];
}
dataGridView1.DataSource = dt;
con.Close();
}
}
}
}
}
I suggest to use a TextBox and set MultiLine to true.
Then you can read all the ids like this:
string[] ids = myTextBox.Text.Split('\n');
EDIT:
You can use SQL's IN to find all elements:
string sql = "SELECT conno, etc FROM BRDATA WHERE conno IN (" + String.Join(", ", ids) + ")";

How to search Multiple Sites using Lucene Search engine API?

Hope that someone can help me as soon as possible :-)
I would like to know how can we search Multiple Sites using Lucene??! (All sites are in one index).
I have succeeded to search one website, and to index multiple sites, however I am not able to search all websites.
Consider this method that I have:
private void PerformSearch()
{
DateTime start = DateTime.Now;
//Create the Searcher object
string strIndexDir = Server.MapPath("index") + #"\" + mstrURL;
IndexSearcher objSearcher = new IndexSearcher(strIndexDir);
//Parse the query, "text" is the default field to search
Query objQuery = QueryParser.Parse(mstrQuery, "text", new StandardAnalyzer());
//Create the result DataTable
mobjDTResults.Columns.Add("title", typeof(string));
mobjDTResults.Columns.Add("path", typeof(string));
mobjDTResults.Columns.Add("score", typeof(string));
mobjDTResults.Columns.Add("sample", typeof(string));
mobjDTResults.Columns.Add("explain", typeof(string));
//Perform search and get hit count
Hits objHits = objSearcher.Search(objQuery);
mintTotal = objHits.Length();
//Create Highlighter
QueryHighlightExtractor highlighter = new QueryHighlightExtractor(objQuery, new StandardAnalyzer(), "<B>", "</B>");
//Initialize "Start At" variable
mintStartAt = GetStartAt();
//How many items we should show?
int intResultsCt = GetSmallerOf(mintTotal, mintMaxResults + mintStartAt);
//Loop through results and display
for (int intCt = mintStartAt; intCt < intResultsCt; intCt++)
{
//Get the document from resuls index
Document doc = objHits.Doc(intCt);
//Get the document's ID and set the cache location
string strID = doc.Get("id");
string strLocation = "";
if (mstrURL.Substring(0,3) == "www")
strLocation = Server.MapPath("cache") +
#"\" + mstrURL + #"\" + strID + ".htm";
else
strLocation = doc.Get("path") + doc.Get("filename");
//Load the HTML page from cache
string strPlainText;
using (StreamReader sr = new StreamReader(strLocation, System.Text.Encoding.Default))
{
strPlainText = ParseHTML(sr.ReadToEnd());
}
//Add result to results datagrid
DataRow row = mobjDTResults.NewRow();
if (mstrURL.Substring(0,3) == "www")
row["title"] = doc.Get("title");
else
row["title"] = doc.Get("filename");
row["path"] = doc.Get("path");
row["score"] = String.Format("{0:f}", (objHits.Score(intCt) * 100)) + "%";
row["sample"] = highlighter.GetBestFragments(strPlainText, 200, 2, "...");
Explanation objExplain = objSearcher.Explain(objQuery, intCt);
row["explain"] = objExplain.ToHtml();
mobjDTResults.Rows.Add(row);
}
objSearcher.Close();
//Finalize results information
mTsDuration = DateTime.Now - start;
mintFromItem = mintStartAt + 1;
mintToItem = GetSmallerOf(mintStartAt + mintMaxResults, mintTotal);
}
As you can see that I use the site URL mstrURL when I create the search object
string strIndexDir = Server.MapPath("index") + #"\" + mstrURL;
How can I do the same when I want to search multiple sites??
Actually I am using this code.
Combine each of your site's Searcher within a MultiSearcher
See this question for more details:
Multiple Indexes search in Lucene.Net

using the TSqlParser

I'm attempting to parse SQL using the TSql100Parser provided by microsoft. Right now I'm having a little trouble using it the way it seems to be intended to be used. Also, the lack of documentation doesn't help. (example: http://msdn.microsoft.com/en-us/library/microsoft.data.schema.scriptdom.sql.tsql100parser.aspx )
When I run a simple SELECT statement through the parser it returns a collection of TSqlStatements which contains a SELECT statement.
Trouble is, the TSqlSelect statement doesn't contain attributes such as a WHERE clause, even though the clause is implemented as a class. http://msdn.microsoft.com/en-us/library/microsoft.data.schema.scriptdom.sql.whereclause.aspx
The parser does recognise the WHERE clause as such, looking at the token stream.
So, my question is, am I using the parser correctly? Right now the token stream seems to be the most useful feature of the parser...
My Test project:
public static void Main(string[] args)
{
var parser = new TSql100Parser(false);
IList<ParseError> Errors;
IScriptFragment result = parser.Parse(
new StringReader("Select col from T1 where 1 = 1 group by 1;" +
"select col2 from T2;" +
"select col1 from tbl1 where id in (select id from tbl);"),
out Errors);
var Script = result as TSqlScript;
foreach (var ts in Script.Batches)
{
Console.WriteLine("new batch");
foreach (var st in ts.Statements)
{
IterateStatement(st);
}
}
}
static void IterateStatement(TSqlStatement statement)
{
Console.WriteLine("New Statement");
if (statement is SelectStatement)
{
PrintStatement(sstmnt);
}
}
Yes, you are using the parser correctly.
As Damien_The_Unbeliever points out, within the SelectStatement there is a QueryExpression property which will be a QuerySpecification object for your third select statement (with the WHERE clause).
This represents the 'real' SELECT bit of the query (whereas the outer SelectStatement object you are looking at has just got the 'WITH' clause (for CTEs), 'FOR' clause (for XML), 'ORDER BY' and other bits)
The QuerySpecification object is the object with the FromClauses, WhereClause, GroupByClause etc.
So you can get to your WHERE Clause by using:
((QuerySpecification)((SelectStatement)statement).QueryExpression).WhereClause
which has a SearchCondition property etc. etc.
Quick glance around would indicate that it contains a QueryExpression, which could be a QuerySpecification, which does have the Where clause attached to it.
if someone lands here and wants to know how to get the whole elements of a select statement the following code explain that:
QuerySpecification spec = (QuerySpecification)(((SelectStatement)st).QueryExpression);
StringBuilder sb = new StringBuilder();
sb.AppendLine("Select Elements");
foreach (var elm in spec.SelectElements)
sb.Append(((Identifier)((Column)((SelectColumn)elm).Expression).Identifiers[0]).Value);
sb.AppendLine();
sb.AppendLine("From Elements");
foreach (var elm in spec.FromClauses)
sb.Append(((SchemaObjectTableSource)elm).SchemaObject.BaseIdentifier.Value);
sb.AppendLine();
sb.AppendLine("Where Elements");
BinaryExpression binaryexp = (BinaryExpression)spec.WhereClause.SearchCondition;
sb.Append("operator is " + binaryexp.BinaryExpressionType);
if (binaryexp.FirstExpression is Column)
sb.Append(" First exp is " + ((Identifier)((Column)binaryexp.FirstExpression).Identifiers[0]).Value);
if (binaryexp.SecondExpression is Literal)
sb.Append(" Second exp is " + ((Literal)binaryexp.SecondExpression).Value);
I had to split a SELECT statement into pieces. My goal was to COUNT how many record a query will return. My first solution was to build a sub query such as
SELECT COUNT(*) FROM (select id, name from T where cat='A' order by id) as QUERY
The problem was that in this case the order clause raises the error "The ORDER BY clause is not valid in views, inline functions, derived tables, sub-queries, and common table expressions, unless TOP or FOR XML is also specified"
So I built a parser that split a SELECT statment into fragments using the TSql100Parser class.
using Microsoft.Data.Schema.ScriptDom.Sql;
using Microsoft.Data.Schema.ScriptDom;
using System.IO;
...
public class SelectParser
{
public string Parse(string sqlSelect, out string fields, out string from, out string groupby, out string where, out string having, out string orderby)
{
TSql100Parser parser = new TSql100Parser(false);
TextReader rd = new StringReader(sqlSelect);
IList<ParseError> errors;
var fragments = parser.Parse(rd, out errors);
fields = string.Empty;
from = string.Empty;
groupby = string.Empty;
where = string.Empty;
orderby = string.Empty;
having = string.Empty;
if (errors.Count > 0)
{
var retMessage = string.Empty;
foreach (var error in errors)
{
retMessage += error.Identifier + " - " + error.Message + " - position: " + error.Offset + "; ";
}
return retMessage;
}
try
{
// Extract the query assuming it is a SelectStatement
var query = ((fragments as TSqlScript).Batches[0].Statements[0] as SelectStatement).QueryExpression;
// Constructs the From clause with the optional joins
from = (query as QuerySpecification).FromClauses[0].GetString();
// Extract the where clause
where = (query as QuerySpecification).WhereClause.GetString();
// Get the field list
var fieldList = new List<string>();
foreach (var f in (query as QuerySpecification).SelectElements)
fieldList.Add((f as SelectColumn).GetString());
fields = string.Join(", ", fieldList.ToArray());
// Get The group by clause
groupby = (query as QuerySpecification).GroupByClause.GetString();
// Get the having clause of the query
having = (query as QuerySpecification).HavingClause.GetString();
// Get the order by clause
orderby = ((fragments as TSqlScript).Batches[0].Statements[0] as SelectStatement).OrderByClause.GetString();
}
catch (Exception ex)
{
return ex.ToString();
}
return string.Empty;
}
}
public static class Extension
{
/// <summary>
/// Get a string representing the SQL source fragment
/// </summary>
/// <param name="statement">The SQL Statement to get the string from, can be any derived class</param>
/// <returns>The SQL that represents the object</returns>
public static string GetString(this TSqlFragment statement)
{
string s = string.Empty;
if (statement == null) return string.Empty;
for (int i = statement.FirstTokenIndex; i <= statement.LastTokenIndex; i++)
{
s += statement.ScriptTokenStream[i].Text;
}
return s;
}
}
And to use this class simply:
string fields, from, groupby, where, having, orderby;
SelectParser selectParser = new SelectParser();
var retMessage = selectParser.Parse("SELECT * FROM T where cat='A' Order by Id desc",
out fields, out from, out groupby, out where, out having, out orderby);