I have a datareader to display a list of gameweeks in a js carousel.
I need to be able to add an if statement to change the div class of the current gameweek.
This is my current code:
if (dReader.HasRows) {
while (dReader.Read()) {
gameweekList.Text += "<div class=\"item\"><h4>Gameweek " +
(dReader["gameweekID"].ToString()) + "</h4></div>";
}
} else {
gameweekList.Text = "Error Finding Gameweeks";
}
dReader.Close();
conn.Close();
In effect I want to add if(dreader[1]) then add the extra bit, how is this possible?
I find it easier to use a DataTable or DataSet. Something like this:
DataTable dt = new DataTable();
dt.Load(dreader)
Then you can more easily reach a certain row using the DataTable.Rows property.
How about...
if (dReader.HasRows) {
while (dReader.Read()) {
if ( dReader["gameweekID"].ToString() == currentWeekId )
{
gameweekList.Text += "<div class=\"somethingSpecial\"><h4>Gameweek " +
(dReader["gameweekID"].ToString()) + "</h4></div>";
}
else
{
gameweekList.Text += "<div class=\"item\"><h4>Gameweek " +
(dReader["gameweekID"].ToString()) + "</h4></div>";
}
}
} else {
gameweekList.Text = "Error Finding Gameweeks";
}
dReader.Close();
conn.Close();
If I got you correctly, you can just count reader reads like this. Then when the count suits you, you can add something different:
int count = 0;
if (dReader.HasRows) {
while (dReader.Read()) {
if(count == 1) //add special row
gameweekList.Text += "something special " + dReader["gameweekID"].ToString();
else
gameweekList.Text += "<div class=\"item\"><h4>Gameweek " +
(dReader["gameweekID"].ToString()) + "</h4></div>";
count++;
}
} else {
gameweekList.Text = "Error Finding Gameweeks";
}
dReader.Close();
conn.Close();
But if you want to have current and subsequent read at the same time you should firs read onceand then start reading in a loop like this:
if (dReader.HasRows) {
string previousRead = string.Empty;
dReader.Read();
previousRead = dReader["gameweekID"].ToString();
while (dReader.Read()) {
//use current and previous read
//dReader["gameweekID"].ToString()
//previousRead
//update previousRead for the next read
previousRead = dReader["gameweekID"].ToString();
}
} else {
gameweekList.Text = "Error Finding Gameweeks";
}
dReader.Close();
conn.Close();
To get the first row, start from 0 and always put it into a Data Tables because you always get problems reading directly from Data Readers;
if (dReader.HasRows) {
DataTable dt = new DataTable();
dt.Load(dreader)
gameweekList.Text = dt.Rows[0]["gameweekID"]
}
Related
I am reading word file and add data after it find Favour. Just wont to add data after favour. First record using this code added perfect record but second time it give Syntax error(operator missing). Please help me to correctly add all records
private void button1_Click(object sender, EventArgs e)
{
try
{
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
object nullobj = System.Reflection.Missing.Value;
object file = openFileDialog1.FileName;
Document doc = app.Documents.Open(#"C:\Users\juilee Raut\Downloads\ITCL-CAES 1 (1).docx");
doc.ActiveWindow.Selection.WholeStory();
doc.ActiveWindow.Selection.Copy();
IDataObject da = Clipboard.GetDataObject();
string text = da.GetData(DataFormats.Text).ToString();
richTextBox1.Text = text;
string data = string.Empty;
string[] data1 = richTextBox1.Lines;
List<string> Info = new List<string>();
int i = 0;
int j = 0;
int m = 0;
while (i < data1.Length)
{
if (data1[i].StartsWith("FAVOUR:"))
{
j++;
if (m == 0)
{
data = data + data1[i].ToString() + Environment.NewLine;
string inf = string.Join(Environment.NewLine, Info.ToArray());
con.Open();
OleDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT into AllData(FullJud) VALUES('" + inf + "')";
cmd.ExecuteNonQuery();
con.Close();
Info.Clear();
inf = string.Empty;
m = 1;
}
}
else
{
m = 0;
if (data1[i] != "")
{
if (data1[i].EndsWith("2017") && data1[i].Length == 10 || data1[i].EndsWith("2016") && data1[i].Length == 10)
{
data = data + data1[i].ToString() + Environment.NewLine + "##ln##" + Environment.NewLine;
Info.Add(data1[i]);
Info.Add("##ln##");
}
else if(data1[i].StartsWith("SECTION:") || data1[i].StartsWith("Section:") || data1[i].StartsWith("SECTION-") || data1[i].Contains("SUBJECT:") || data1[i].StartsWith("Subject:") || data1[i].StartsWith("SUBJECT-") || data1[i].StartsWith("SUBJECTS:"))
{
data = data + data1[i].ToString() + Environment.NewLine;
}
else if(data1[i].EndsWith("Respondent.") || data1[i].EndsWith("Petitioner.") || data1[i].EndsWith("Appellant.") || data1[i].EndsWith("Appellant") || data1[i].EndsWith("Respondent") || data1[i].EndsWith("Counsel,"))
{
data = data + data1[i].ToString() + Environment.NewLine;
}
else
{
data = data + data1[i].ToString() + Environment.NewLine;
Info.Add(data1[i]);
}
}
}
i++;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This is the error I get:
"Syntax error (missing operator) in query expression ''391 ITR 382 (BOM): 88 TAXMANN.COM 556\r\nHIGH COURT OF BOMBAY \r\nM.S. SANKLECHA AND A.K. MENON, JJ.\r\nMalay N. Sanghvi v/s. Income Tax Officer\r\nIT APPEAL NO. 1342 OF 2014\r\n31.01.2017\r\n##ln##\r\nSection 80-IB of the Income-tax Act, 1961 - Deductions - Profits a'."
What if Info contains several values, let's say:
Info = { "value1", "value2" }
Then, inf would be:
inf = "value1\r\nvalue2"
Therefore, cmd.CommandText would be:
cmd.CommandText = "INSERT into AllData(FullJud) VALUES('value1\r\nvalue2')";
and I'm quite sure this is not the wanted behaviour.
Edit
What if one value in Info contained a ' character?
Info = { "val'ue" }
Then, inf would be:
inf = "val'ue"
Therefore, cmd.CommandText would be:
cmd.CommandText = "INSERT into AllData(FullJud) VALUES('val'ue')";
// SQL won't understand that part --------------------------|||
and that's where you get an error.
Moreover, what if Info had the following value instead:
Info = { "value1');DROP TABLE [anytable];--" }
That's typical SQL Injection.
Some questions/comments:
What is j used for?
What is the purpose of inf = string.Empty;? It is a local variable and will be garbage collected.
What is the purpose of data? Will you even use it at some point?
You are using a while loop when you could be using a for(int i=0;i<data1.Length;i++) loop.
What if data1 contains two consecutive strings starting with "FAVOUR:"? Why would you insert only the first one, and not the second one?
else
{
data.Replace("'", "/");
data1[i] = data1[i].Replace("'","/");
Info.Add(data1[i]);
data = data + data1[i].ToString() + Environment.NewLine;
}
In else part I just replace the ' to / and my problem is solve
I don't know why this code gives me an error.
I am trying to put the sql commands into a transaction.
This code gives me this error.
I can't fill int anything else at the source than this.
This is the error I get
Additional information: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
using (SQLiteConnection cn = new SQLiteConnection(string.Format("Data Source={0};")))
{
cn.Open();
using (SQLiteTransaction tr = cn.BeginTransaction())
{
sqlTarget = sqlInsert1 + columnList + ") VALUES (";
object[] sourceVal = new object[nCol];
rdrSourceTable.GetValues(sourceVal);
string strMsg = string.Empty;
int iCol = 0;
foreach (object col in sourceVal)
{
string columnName = rdrSourceTable.GetName(iCol++);
sqlTarget += objDbTarget.ObjectForSql(col, ref strMsg, false, columnName) +
comma;
}
if (strMsg.Length > 0)
{
msg = string.Format(
"The input values are wrong, strMsg = {0}\r\nThe composed sql = {1}",
strMsg, sqlTarget);
if (m_interactive)
{
DialogResult res = MessageBox.Show(msg, GetType().ToString(),
MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (res == DialogResult.Cancel)
{
throw new CopyDbContentsException(msg);
}
}
if (errorCount++ < 5)
{
RadFile.WriteLogMsg("FillTableWithInsertCommands. " + msg +
"\r\n\r\nContinue?");
}
//Skip the insert action because of the error and go to next row.
continue;
}
sqlTarget = sqlTarget.Substring(0, sqlTarget.Length - comma.Length) + ")";
objDbTarget.ExecuteActionQuery(sqlTarget);
iRow++;
int remainder = iRow%250;
if (remainder == 0)
{
WriteStatusLabel(string.Format(
"Copy the rows of table {0}. {1:N0} written.", Name,
iRow));
}
remainder = iRow%nMsgMod;
if (remainder == 0)
{
msg = string.Format("{0:N0} rows of table {1} copied.",
iRow, Name);
RadFile.WriteLogMsg(msg, withHeader: false);
if (nMsgMod < 100000 && iRow == 10*nMsgMod)
{
nMsgMod *= 10;
}
}
tr.Commit();
}
cn.Close();
}
}
msg = string.Format("Table {0} is copied, {1:N0} rows. ", Name, iRow);
if (errorCount > 0)
{
msg += errorCount;
msg += (errorCount == 1) ? " row is" : " rows are";
msg += " skipped because of errors in the input";
}
RadFile.WriteLogMsg(msg, withHeader: false);
}
}
you expect this to work?
SQLiteConnection cn = new SQLiteConnection(string.Format("Data Source={0};"))
here is a good explaination about SQLite ConnectionStrings
https://www.connectionstrings.com/sqlite/
i assume you want to do something like
var cn = new SQLiteConnection(string.Format("Data Source={0};Version=3;", #"c:\mydb.db"))
And the Error
Additional information: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
says that string.Format("Data Source={0};") want's to access the first item at index 0, which is not provided by you
Its at the 1st line:
string.Format("Data Source={0};"
you must provide argument for string format , for example :
string.Format("Data Source={0};","my data source")
where "my data source" will be your database data source name.
Man, you should refactor all this code. But for you problem, this is the solution:
using (SQLiteConnection cn = new SQLiteConnection("put your entire connection string here"))
see this for more information on how to use string.Format method.
I want to use textbox and checkboxlist to search data in gridview using asp.net c#. Using textbox can search the data. But for checkboxlist only can search the data when check only one checkbox. If check more than one checkbox, can't search the data. thanks a lot for helping.
the code:
c# code
protected void btnSearch_Click(object sender, EventArgs e)
{
if (cblDay.SelectedIndex != -1)
{
foreach (ListItem val in cblDay.Items)
{
if (val.Selected == true)
{
RptRateData.Day += val.Value + "";
}
}
}
RptRateData.RateAmount = txtRate.Text.Trim();
BindGrid();
}
code for class:
public string RateAmount { get; set; }
public string Day { get; set; }
internal DataSet GetRptRateSet()
{
DataSet tmpDS = new DataSet();
try
{
string strSQL = #"SELECT ComplexRateInfo.ComplexRateId,
ComplexRateDetailInfo.Day,
ComplexRateInfo.RateAmount
FROM ComplexRateInfo
LEFT JOIN ComplexRateDetailInfo ON ComplexRateInfo.ComplexRateId = ComplexRateDetailInfo.ComplexRateId ";
string whereSQL = " WHERE";
string orderBySQL = " order by Day ;";
int filterCount = 0; //to keep track of needed filter that are going to be used by the sql string
string[] sIndex = new string[2]; //to keep track of scalar variable needed by the sql, four string of sIndex because maximum filter available is 4
int indexCount = 0; //count to access sIndex members
//filter with or without day
if (_ds.Day != null && _ds.Day != "")
{
if (filterCount > 0) //query need additional filter
whereSQL = whereSQL + " AND ComplexRateDetailInfo.Day LIKE '{" + filterCount + "}'";
else //if this is the first filter
whereSQL = whereSQL + " ComplexRateDetailInfo.Day LIKE '{" + filterCount + "}'";
filterCount++;
sIndex[indexCount] = _ds.Day;
indexCount++;
}
//filter with or without rate amount
if (_ds.RateAmount != null && _ds.RateAmount != "")
{
if (filterCount > 0) //query need additional filter
whereSQL = whereSQL + " AND ComplexRateInfo.RateAmount LIKE '{" + filterCount + "}'";
else //if this is the first filter
whereSQL = whereSQL + " ComplexRateInfo.RateAmount LIKE '{" + filterCount + "}'";
filterCount++;
sIndex[indexCount] = _ds.RateAmount;
indexCount++;
}
//build complete query with no filter at all
if (filterCount == 0)
{
strSQL = strSQL + orderBySQL;
tmpDS = Db.GetDataSet(string.Format(strSQL));
}
//build complete query with 1 or more filter
else
{
strSQL = strSQL + whereSQL + orderBySQL;
tmpDS = Db.GetDataSet(string.Format(strSQL, sIndex));
}
}
catch (Exception ex)
{
throw ex;
}
return tmpDS;
}
There are two mistakes in your code.
Assigning values to RptRateData.Day from CheckBoxList.
Description: You assign selected values to object without using any separator. So For example if you have selected 1, 2, 4 days then as per your code, value of RptRateData.Day will be 124. Instead of that, it should be separated with comma as shown below:
var selectedDays = string.Empty;
foreach (ListItem val in cblDay.Items)
{
if (val.Selected == true)
{
selectedDays += "'" + val.Value + "',";
}
}
RptRateData.Day = selectedDays.TrimEnd(new char[] { ',' });
Now come to the second point which is in your SQL query which you make dynamically.
Description: In this query in WHERE clause you use Like operator for ComplexRateDetailInfo.Day. This will not work anymore. Instead of that you should use IN operator.
Note: Are you sure that your Like operator is working with curly braces ('{' and '}') and without '%' symbol ?
I am reading a file from which I create a dataset and I need to create a report from that dataset but this code is not working. so maybe someone could tell me what I am doing wrong I would really apreciated it or suggest another approach to this issue.
The BuildataSet function is working properly, creating the report its whats giving me problems.
public DataSet BuildDataSet(string file,string tableName,string delimeter)
{
//create our DataSet
DataSet domains = new DataSet();
//add our table
domains.Tables.Add(tableName);
String c = "VOYAGE|SAILDATE|DELIVERYDATE|AMENITY|QTY|COMPLIMENTS|MESSAGE|CABIN|1STPAXNAME|"
+"1STPAXLAST|2NDPAXNAME|2NDPAXLAST|3RDPAXNAME|3RDPAXLAST|4THPAXNAME|4THPAXLAST|SHIP|TYPE|DELIVERYTYPE|DROOM|SEATING|TABLE|GHOSTCOLUMN";
try
{
//first make sure the file exists
if (File.Exists(file))
{
//create a StreamReader and open our text file
StreamReader reader = new StreamReader(file);
//read the first line in and split it into columns
string [] columns = c.Split('|');
//now add our columns (we will check to make sure the column doesnt exist before adding it)
foreach (string col in columns)
{
//variable to determine if a column has been added
bool added = false;
string next = "";
//our counter
int i = 0;
while (!(added))
{
string columnName = col;
//now check to see if the column already exists in our DataTable
if (!(domains.Tables[tableName].Columns.Contains(columnName)))
{
//since its not in our DataSet we will add it
domains.Tables[tableName].Columns.Add(columnName, typeof(string));
added = true;
}//end if
else
{
//we didnt add the column so increment out counter
i++;
next = "_" + i.ToString();
break;
}//end else
}
}
//now we need to read the rest of the text file
string data = reader.ReadToEnd();
//now we will split the file on the carriage return/line feed
//and toss it into a string array
string [] rows = data.Split("\r".ToCharArray());
//now we will add the rows to our DataTable
foreach (string r in rows)
{
string[] items = r.Split(delimeter.ToCharArray());
//split the row at the delimiter
//for (int i = 0; i <= items.Count() - 1; i++)
//{
domains.Tables[tableName].Rows.Add(items);
//}
}
}
else
{
throw new FileNotFoundException("The file " + file + " could not be found");
}
}
catch (FileNotFoundException ex)
{
_message = ex.Message;
return null;
}
catch (Exception ex)
{
_message = ex.Message;
return null;
}
//now return the DataSet
return domains;
}
//#endregion
protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds = BuildDataSet(#"C:/Documents/GIFTCDS.TXT", "MyNewTable", "|");
GridView1.DataSource = ds;
GridView1.DataBind();
ReportDataSource rds = new ReportDataSource("MyNewTable", ds.Tables[0]);
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(rds);
ReportViewer1.DataBind();
ReportViewer1.LocalReport.Refresh();
}
The data reader named eventreader can be empty and i'm trying to work out an appropriate statement to detect if the datareader contains rows and if the require record exists.
oledbexecute("SELECT [Unit No] FROM UnitOpenAtEvent WHERE [Event ID]='" + strDate + "'");
eventReader = dbcommand.ExecuteReader();
for (int i = 0; i < checkboxEvent.Items.Count; i++)
{
if (checkboxEvent.GetItemCheckState(i) == CheckState.Checked)
{
if (eventReader["Unit No"] != DBNull.Value)
{
while (eventReader.Read())
{
if (eventReader["Unit No"].ToString() == checkboxEvent.Items[i].ToString())
{
oledbexecute("INSERT INTO UnitOpenAtEvent ([Event ID],[Unit No]) VALUES ('" + strDate + checkboxEvent.Items[i].ToString() + "'");
intReader = dbcommand.ExecuteNonQuery();
}
}
}
else
{
oledbexecute("INSERT INTO UnitOpenAtEvent ([Event ID],[Unit No]) VALUES ('" + strDate + checkboxEvent.Items[i].ToString() + "'");
intReader = dbcommand.ExecuteNonQuery();
}
}
else if (checkboxEvent.GetItemCheckState(i) == CheckState.Unchecked)
{
// this is effectively a copy of above
}
}
You can check if the DataReader has any rows using e.g.
if (eventReader.HasRows)
Update:
Following from comment below re: IDataReader...
You could do something like this (shortened to include the most relevant bits for conciseness)
eventReader = dbcommand.ExecuteReader();
bool hasRow = eventReader.Read();
if (hasRow)
{
for (int i = 0; i < checkboxEvent.Items.Count; i++)
{
...
...
while (hasRow)
{
// Code in here to deal with each row
hasRow = eventReader.Read();
}
}
}
You may be misunderstanding how IDataReader.Read() works.
From that help page:
Return Value
Type: System.Boolean
true if there are more rows; otherwise, false.
and
The default position of the IDataReader is prior to the first record.
Therefore you must call Read to begin accessing any data.
So when you first get a datareader it won't be pointing to any data. If you call .Read() it will return true if there is a row to move to and move to it and if there are no rows it will return false.