header and footer in text file using c# - c#

I am newbie to c# I want to have headers and footers when saving the text file which is generated on the data grid view.
when I run a sql query it should generate 3 column values as headers and 3 columns values as footers.
headers recordtype,cpcnumber,filesequence number;
footers record type,no of requests,total court fee,claim amount; I don't how to get these records when i run this command as headers/footers. Any help would be greatly appreciated..
private void btnGetData_Click(object sender, EventArgs e)
{
this.btnGetData.Enabled = false;
Application.DoEvents();
string stringSql = " SELECT distinct " +
"'" + comboBox6.Text + "' as RecordType" +
" , left([CPC No] +' ',30) " +
" , space(1983) " +
",'" + comboBox6.Text + " 'as RecordType" +
, left(t.t_reference + ' ' ,24 ) as ClaimantReference " +
" , left([Claim Number] +' ',30) " +
" , " + comboBox4.Text + " as CourtCode" +
" ,left(ta_title +' ',30) as Title " +
" ,left(ta_surname +' ',30) as Surname " +
", space(180), bat.PCN_Charge as ClaimAmount " +
",[Court Fee] " +
",[Solictors Fees]" +
", (bat.PCN_Charge + [Court Fee]) as TotalAmount" +
",[POC1]" +
",'" + textBox2.Text + "' as RequestType" +
//",'" + comboBox1.Text + "' as RecordType" +
",'" + textBox3.Text + "' as TotalCourtFee" +
",'" + textBox4.Text + "' as TotalClaimAmount" +
" , space(1966) " +
" FROM tickets t " +
" LEFT OUTER JOIN " +
"( " +
" SELECT ticket_addresses.ta_system_ref, ta_title, ta_othername, ta_surname, ta_house_number, ta_address_1, ta_address_2, " +
" ta_address_3, ta_address_4, ta_post_code, ta_telephone, ta_organisation " +
" FROM ticket_addresses " +
" INNER JOIN " +
" ( " +
" SELECT ticket_addresses.ta_system_ref, MAX(ta_address_code) AS ta_address_code " +
" FROM ticket_addresses " +
" GROUP BY ta_system_ref " +
" ) ad " +
" ON (ticket_addresses.ta_system_ref=ad.ta_system_ref AND ticket_addresses.ta_address_code=ad.ta_address_code) " +
")ta " +
"ON (t.t_number=ta.ta_system_ref) " +
" " +
" Inner JOIN " +
" ticket_hold_record b " +
" ON ( t.t_number = b.thr_system_ref) " +
" " +
"Inner JOIN " +
"Rpt_PCNBalance_ALLTickets bat " +
"ON (t.t_number = bat.t_number) " +
" " +
"Inner JOIN " +
"hold_reasons ch " +
"ON (b.thr_hold_type = ch.hr_code) " +
" " +
"Inner JOIN " +
" [VCS].[dbo].[Courtfees] cf " +
" ON (bat.Payments >= cf. [Min ClaimAmount]) and (bat.Payments <= cf.[Max Claim Amount]) " +
" " +
"Inner JOIN " +
" [VCS].[dbo].[sites] s " +
" ON (t.t_contract = s.Contract) " +
" " +
"Inner JOIN " +
" [VCS].[dbo].[claim info] cc " +
" ON (cc.Code COLLATE DATABASE_DEFAULT = t.t_offence_code COLLATE DATABASE_DEFAULT) " +
" and t.t_reference IN {where} ";
//Generate list of Ticket IDS for SQL Where Clause
string whereClause = "";
string[] tempArray = new string[this.txt.Lines.Length];
tempArray = this.txt.Lines;
if (this.txt.Lines.Length == 0)
{
return;
}
for (int counter = 0; counter <= tempArray.Length-1; counter++)
{
if (tempArray[counter].Trim().Length > 0)
{
whereClause = whereClause + "'" + tempArray[counter] + "'" + ", ";
}
}
whereClause = whereClause.TrimEnd(' ', ',');
whereClause = "(" + whereClause + ")";
stringSql = stringSql.Replace("{where}", whereClause);
myDataset = new DataSet("SQL");
SqlConnection myConn = new SqlConnection();
SqlCommand myCommand = new SqlCommand();
myCommand.CommandType = CommandType.Text;
myCommand.CommandText = stringSql;
myCommand.Connection = myConn;
SqlDataAdapter myAdapter = new SqlDataAdapter();
myAdapter.SelectCommand = myCommand;
myAdapter.Fill(myDataset);
this.dataGridView1.DataSource = myDataset.Tables[0];
for (int counter = 0; counter < myDataset.Tables[0].Columns.Count; counter++)
{
this.dataGridView1.Columns[counter].SortMode = DataGridViewColumnSortMode.NotSortable;
}
this.dataGridView1.Refresh();
myConn.Close(); this.btnGetData.Enabled = true;
this.btnSave.Enabled = true;
Application.DoEvents();
}

Related

Error with SQL Server request using data.sqlclient in UWP

I am trying to run a SQL query on my UWP code. I don't use Linq or EF. The connection to the base work and the simple requests work. This causes me problems: in a first time i populate a listview with the result of a simple request, i choose an element and i click on a searchin button. This request is call with an error:
static public ObservableCollection GetGaz(string connectionString,
string selectedOrder)
{
string GetGazQuery =
"SELECT " +
"tbl_607_gaz_type.gaz_type," +
"tbl_607_theorical_content.theorical_content," +
"tbl_607_made_tolerance.made_tolerance," +
"tbl_607_order_details.gaz_lifetime," +
"tbl_607_gaz.gaz_comments," +
"tbl_607_order_details.FK_ID_order," +
"tbl_607_order_details.poste_number, " +
"tbl_607_order.order_number" +
"FROM " +
"tbl_607_provider join tbl_607_order on tbl_607_provider.ID = tbl_607_order.FK_ID_provider " +
"join tbl_607_order_details on tbl_607_order.ID = tbl_607_order_details.FK_ID_order" +
"join tbl_607_gaz on tbl_607_order_details.FK_ID_gaz = tbl_607_gaz.ID " +
"join tbl_607_gaz_type on tbl_607_gaz.FK_ID_gaz_type = tbl_607_gaz_type.ID " +
"join tbl_607_made_tolerance on tbl_607_gaz.FK_ID_made_tolerence = tbl_607_made_tolerance.ID " +
"join tbl_607_theorical_content on tbl_607_gaz.FK_ID_theorical_content = tbl_607_theorical_content.ID " +
"WHERE " +
"tbl_607_order.order_number" + " LIKE " + "'%" + selectedOrder + "%'";
ObservableCollection GazList = new ObservableCollection();
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
if (conn.State == System.Data.ConnectionState.Open)
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = GetGazQuery;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Gaz gaz = new Gaz
{
Gaz_type = reader.GetString(0),
Theorical_content = reader.GetString(1),
Made_tolerance = reader.GetDouble(2),
Gaz_lifetime = reader.GetInt32(3),
Gaz_comments = reader.GetString(4),
Poste_number = reader.GetInt32(6)
};
GazList.Add(gaz);
}
}
}
}
}
return GazList;
}
catch (Exception eSql)
{
Debug.WriteLine("Exception: " + eSql.Message);
}
return null;
}
}
private string selectedOrder;
public Gestion_Stock()
{
this.InitializeComponent();
SelectOrders.ItemsSource = OrdersDataHelper.GetOrders(connectionString: (Windows.UI.Xaml.Application.Current as App).ConnectionString);
}
private void Search_Click(object sender, RoutedEventArgs e)
{
Affichage_Stock_Gaz.ItemsSource = GazDataHelper.GetGaz((Windows.UI.Xaml.Application.Current as App).ConnectionString, selectedOrder);
}
private void SelectOrders_SelectionChanged (object sender, SelectionChangedEventArgs e)
{
ListView selectOrders = sender as ListView;
Orders orders = SelectOrders.SelectedItem as Orders;
selectedOrder = orders.Order_Number;
}
The output:
Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.SqlClient.dll
Exception: Incorrect syntax near the keyword 'join'
This simple request is working, i don't use a variable and "where" command.
This work:
static public ObservableCollection GetOrders(string connectionString)
{
const string GetOrdersQuery = "" +
"select " +
"tbl_607_order.start_date," +
"tbl_607_order.end_date," +
"tbl_607_provider.provider_name," +
"tbl_607_order.order_number," +
"tbl_607_order.shipping_request_active," +
"tbl_607_order.item_reception_active " +
"from " +
"tbl_607_provider join tbl_607_order on tbl_607_provider.ID = tbl_607_order.FK_ID_provider "
;
Someone would have any idea?
Thanks a lot!
Add the missing space by changing
"SELECT " +
"tbl_607_gaz_type.gaz_type," +
"tbl_607_theorical_content.theorical_content," +
"tbl_607_made_tolerance.made_tolerance," +
"tbl_607_order_details.gaz_lifetime," +
"tbl_607_gaz.gaz_comments," +
"tbl_607_order_details.FK_ID_order," +
"tbl_607_order_details.poste_number, " +
"tbl_607_order.order_number" +
"FROM " +
"tbl_607_provider join tbl_607_order on tbl_607_provider.ID = tbl_607_order.FK_ID_provider " +
"join tbl_607_order_details on tbl_607_order.ID = tbl_607_order_details.FK_ID_order" +
"join tbl_607_gaz on tbl_607_order_details.FK_ID_gaz = tbl_607_gaz.ID " +
"join tbl_607_gaz_type on tbl_607_gaz.FK_ID_gaz_type = tbl_607_gaz_type.ID " +
"join tbl_607_made_tolerance on tbl_607_gaz.FK_ID_made_tolerence = tbl_607_made_tolerance.ID " +
"join tbl_607_theorical_content on tbl_607_gaz.FK_ID_theorical_content = tbl_607_theorical_content.ID " +
"WHERE " +
"tbl_607_order.order_number" + " LIKE " + "'%" + selectedOrder + "%'";
to
"SELECT " +
"tbl_607_gaz_type.gaz_type," +
"tbl_607_theorical_content.theorical_content," +
"tbl_607_made_tolerance.made_tolerance," +
"tbl_607_order_details.gaz_lifetime," +
"tbl_607_gaz.gaz_comments," +
"tbl_607_order_details.FK_ID_order," +
"tbl_607_order_details.poste_number, " +
"tbl_607_order.order_number" +
"FROM " +
"tbl_607_provider join tbl_607_order on tbl_607_provider.ID = tbl_607_order.FK_ID_provider " +
"join tbl_607_order_details on tbl_607_order.ID = tbl_607_order_details.FK_ID_order " + // note the missing space added here
"join tbl_607_gaz on tbl_607_order_details.FK_ID_gaz = tbl_607_gaz.ID " +
"join tbl_607_gaz_type on tbl_607_gaz.FK_ID_gaz_type = tbl_607_gaz_type.ID " +
"join tbl_607_made_tolerance on tbl_607_gaz.FK_ID_made_tolerence = tbl_607_made_tolerance.ID " +
"join tbl_607_theorical_content on tbl_607_gaz.FK_ID_theorical_content = tbl_607_theorical_content.ID " +
"WHERE " +
"tbl_607_order.order_number" + " LIKE " + "'%" + selectedOrder + "%'";

DatagridView boolean values update to database

I'm having an issue when I update values from a datagridview row to the database. The issue is that I have designed the table in the DB with certain fields as "bit" data type to store boolean value flags.
When i assign the datatable to the datagridview the system aytomatically displays these certain fields as checkboxes, which suits me just fine.
But when I try to update these values back to the database the boolean values go bananas.....Here is my code...
int fragileChk = (Convert.ToBoolean(aRow.Cells[12].Value) ? 1 : 0);
int inflamChk = (Convert.ToBoolean(aRow.Cells[13].Value) ? 1 : 0);
int biologicalChk = (Convert.ToBoolean(aRow.Cells[15].Value) ? 1 : 0);
int emergencyChk = (Convert.ToBoolean(aRow.Cells[16].Value) ? 1 : 0);
int usedChk = (Convert.ToBoolean(aRow.Cells[25].Value) ? 1 : 0);
int offerChk = (Convert.ToBoolean(aRow.Cells[27].Value) ? 1 : 0);
string err;
string sqlComm = "UPDATE [70_warehouse_lines] SET " +
"ProductDescr = '" + aRow.Cells[5].Value.ToString() + "', " +
"PartNumber = '" + aRow.Cells[6].Value.ToString() + "', " +
"SerialNumber = '" + aRow.Cells[7].Value.ToString() + "', " +
"Quanitity = " + aRow.Cells[8].Value + ", " +
"Weight = " + aRow.Cells[10].Value + ", " +
"FragileFlag = " + fragileChk + ", " +
"InflammableFlag =" + inflamChk + ", " +
"BiologicalFlag = " + biologicalChk + ", " +
"EmergencyFlag = " + emergencyChk + ", " +
"SpecialInstructions = '" + aRow.Cells[17].Value.ToString() + "', " +
"ShopCostPrice = " + aRow.Cells[19].Value + ", " +
"RetailPrice1 = " + aRow.Cells[20].Value + ", " +
"RetailPrice2 = " + aRow.Cells[21].Value + ", " +
"WholePrice1 = " + aRow.Cells[22].Value + ", " +
"WholePrice2 = " + aRow.Cells[23].Value + ", " +
"CalculatedPrice = " + aRow.Cells[24].Value + ", " +
"UsedParts = " + usedChk + ", " +
"TimesProcessed = " + aRow.Cells[26].Value + ", " +
"OnOffer = " + offerChk + ", " +
"NotesPerPart = '" + aRow.Cells[28].Value.ToString() + "' " +
"WHERE WarehouseLineID = '" + aRow.Cells[0].Value.ToString() + "'";
myConn.ExecSqlCmd(sqlComm, out err);
any ideas ? (I have declared int values just for diagnostic purposes. Thank you in advance for your help.
Always use parameterised query, Using parameters helps prevent SQL Injection attacks when the database is used in conjunction with a program interface.
also you can specify datatype in parameterised query that will helpfull in your case.
string sqlComm = "UPDATE [70_warehouse_lines] SET " +
"ProductDescr = #ProductDescr " +
"PartNumber = #PartNumber " +
"SerialNumber = #SerialNumber " +
"Quanitity = #Quanitity" +
"Weight = #Weight" +
"FragileFlag = #FragileFlag" +
"InflammableFlag = #InflammableFlag" +
"BiologicalFlag = #BiologicalFlag" +
"EmergencyFlag = #EmergencyFlag" +
"SpecialInstructions = #SpecialInstructions " +
"ShopCostPrice = #ShopCostPrice" +
"RetailPrice1 = #RetailPrice1" +
"RetailPrice2 = #RetailPrice2 " +
"WholePrice1 = #WholePrice1 " +
"WholePrice2 = #WholePrice2 " +
"CalculatedPrice = #CalculatedPrice " +
"UsedParts = #UsedParts " +
"TimesProcessed = #TimesProcessed " +
"OnOffer = #OnOffer " +
"NotesPerPart = #NotesPerPart" +
"WHERE WarehouseLineID = #WarehouseLineID ";
MySqlCommand cmd = new MySqlCommand(sqlComm);
cmd.Parameters.Add("#FragileFlag", MySqlDbType.Bit).Value = (Convert.ToBoolean(aRow.Cells[12].Value) ? 1 : 0);
cmd.Parameters.Add("#InflammableFlag", MySqlDbType.Bit).Value=(Convert.ToBoolean(aRow.Cells[13].Value) ? 1 : 0);
cmd.Parameters.Add("#BiologicalFlag", MySqlDbType.Bit).Value=(Convert.ToBoolean(aRow.Cells[15].Value) ? 1 : 0);
cmd.Parameters.Add("#EmergencyFlag", MySqlDbType.Bit).Value = (Convert.ToBoolean(aRow.Cells[16].Value) ? 1 : 0);
....................................
....................................
....................................
and so on
cmd.ExecuteNonQuery();

Is It possible that heavy query caused to stopped running subsequent code in asp.net?

I have a query in my Asp.net project, which create two table and then insert amount of date into it, when there are afew data so there is no problem, it is my query :
protected void btnLottryInformationSave_Click(object sender, EventArgs e)
{
try
{
int rowCount;
var finalTempTableName = FindTableName();
var selecterServicesList = cblServices.Items.Cast<ListItem>().Where(x => x.Selected).ToList();
var selectedServices = selecterServicesList.Aggregate(string.Empty, (current, service) => current + ("'" + service.Value + "',")).TrimEnd(',');
var tempTableName = "Temp_" + finalTempTableName;
var drawQuery = " if (OBJECT_ID('Temp.dbo." + tempTableName + "') is not null) \ndrop table Temp.dbo." + tempTableName + ";\n";
drawQuery += " create table Temp.dbo." + tempTableName + "(Number char(11) primary key,RepCount int);\n";
drawQuery += " if (OBJECT_ID('Temp.dbo." + finalTempTableName + "') is not null) \ndrop table Temp.dbo." + finalTempTableName + ";\n";
drawQuery += " create table Temp.dbo." + finalTempTableName + "(Id int identity(1,1) primary key,Number char(11));\n";
drawQuery += " select org.orig \n" +
" into #MoOrig \n" +
" from VSReceiveSend.dbo.OrigPrices org \n" +
" INNER JOIN VSReceiveSend.dbo.Services s on (s.Orig = org.Orig) \n" +
" where s.Code in (" + selectedServices + ") and org.MTPrice <> 0 \n ";
if (drpLotteryType.SelectedValue == "1" || drpLotteryType.SelectedValue == "2")
{
drawQuery += " INSERT INTO Temp.dbo." + tempTableName + " (Number,RepCount)\n" +
" select number," + (drpLotteryType.SelectedValue == "1" ? "1" : "sum(c) ") +
" from (\n" +
" SELECT Number,COUNT(*) c \n" +
" FROM VSReceiveSend.dbo.ReceivedSMS with(nolock)\n" +
" INNER JOIN VSReceiveSend.dbo.#MoOrig org ON (org.Orig = ReceivedSMS.Orig) \n " +
" WHERE Date BETWEEN '" + dtpStartDate.Text + "' AND '" + dtpEndDate.Text + "' \n" +
" GROUP BY Number\n" +
" union all \n " +
" SELECT Number,COUNT(*) c \n" +
" FROM VSReceiveSend.dbo.SentSMS with(nolock) \n" +
" INNER JOIN VSReceiveSend.dbo.OrigPrices org ON (org.Orig = SentSMS.Orig AND org.MTPrice <> 0 ) \n " +
" WHERE SentDate BETWEEN '" + dtpStartDate.Text + "' AND '" + dtpEndDate.Text + "' AND SentSMS.ServiceCode in (" + selectedServices + ") \n" +
" GROUP BY Number \n" +
" ) DerivedTable \n" +
" group by number \n" +
((drpLotteryType.SelectedValue == "2" && txtMinAnswerCount.Text != "") ? "HAVING sum(c) >= " + txtMinAnswerCount.Text : "") + ";\n";
}
else if (drpLotteryType.SelectedValue == "3")
{
var pointCount = int.Parse(txtMinCustomerPoint.Text);
drawQuery += " INSERT INTO Temp.dbo." + tempTableName + " ( Number,RepCount)\n" +
" SELECT Number,SUM(Point) / " + txtDivPoints.Text + " RepCount " +
" FROM VsReceiveSend.dbo.SubscriberMatchHistory with(nolock) \n" +
" where ServiceCode in (" + selectedServices + ") and SUBSTRING(DateTime,1,10) BETWEEN '" + dtpStartDate.Text + "' AND '" + dtpEndDate.Text + "' \n" +
" GROUP BY Number\n" +
" HAVING SUM(Point) >= " + pointCount + ";\n";
}
drawQuery += " with DrawInfo (Number,RepCount) as \n" +
"( select Number,1 \n" +
" from temp.dbo." + tempTableName + "\n" +
" union all \n" +
" select DrawInfo.Number,DrawInfo.RepCount + 1 \n" +
" from Temp.dbo." + tempTableName + "\n" +
" inner join DrawInfo on (DrawInfo.Number = Temp.dbo." + tempTableName + ".Number and DrawInfo.RepCount + 1 <= " + tempTableName + ".RepCount) \n" +
")\n" +
" Insert into Temp.dbo." + finalTempTableName + "(Number) \n" +
" select DrawInfo.Number \n" +
" from DrawInfo";
if (!checkBoxOrderInformation.Checked)
drawQuery += " ORDER BY ABS(CAST(CAST(NEWID() AS VARBINARY) AS INT)) \n";
else
drawQuery += " ORDER BY Number \n";
drawQuery += " option (maxrecursion 0);\n " +
" select count(*) from Temp.dbo." + finalTempTableName;
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["VasunReportConnectionString"].ConnectionString))
{
var command = new SqlCommand(drawQuery, connection) { CommandTimeout = 999999999 };
connection.Open();
drawFieldSet.Visible = true;
rowCount = (int)command.ExecuteScalar();
txtNumberOfRow.Text = rowCount.ToString(CultureInfo.InvariantCulture);
}
using (var dbs = new ReceiveSendEntitiesV5())
{
var matchDrawHistories = new MatchDrawHistory()
{
DrawStartDate = dtpStartDate.Text,
DrawEndDate = dtpEndDate.Text,
DrawTime = DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString(),
RowNumber = rowCount,
ServiceCode = cblServices.SelectedValue,
TableName = finalTempTableName
};
dbs.MatchDrawHistories.Add(matchDrawHistories);
dbs.SaveChanges();
}
}
catch (Exception exp)
{
ErrorLabel.Text = "Exception :" + exp.Message;
}
}
but when there were a lot of data, my code execute until : txtNumberOfRow.Text = rowCount.ToString(CultureInfo.InvariantCulture);
so these codes does not execute :
using (var dbs = new ReceiveSendEntitiesV5())
{
var matchDrawHistories = new MatchDrawHistory()
{
DrawStartDate = dtpStartDate.Text,
DrawEndDate = dtpEndDate.Text,
DrawTime = DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString(),
RowNumber = rowCount,
ServiceCode = cblServices.SelectedValue,
TableName = finalTempTableName
};
dbs.MatchDrawHistories.Add(matchDrawHistories);
dbs.SaveChanges();
}
how it is possible!!! what is the problem???

How to populate treenode from SQL using C#

I inherited a project that is populating TreeNode from SQL. I want to add three columns but syntax checker doesn't like what I'm adding but appears consistent with examples in blogs.
TreeNode field = new TreeNode(rdr["VistaFieldNumber"].ToString() + " - " + rdr["VistaFieldName"].ToString()); // current working code
TreeNode field = new TreeNode(rdr["VistaFieldNumber"].ToString() + " - " + rdr["VistaFieldName"].ToString() + " - " + rdr["FieldType"].ToString() + " - " + rdr["PointsToFileNumber"].ToString() + " - " + rdr["FieldLength"].ToString()); //possible replacement code that works but I would have to parse it later
TreeNode field = new TreeNode(rdr["VistaFieldNumber"].ToString() + " - " + rdr["VistaFieldName"].ToString(), rdr["FieldType"].ToString(), rdr["PointsToFileNumber"].ToString(), rdr["FieldLength"].ToString()); //bad syntax beginning at first comma
Method:
private void getFileManFields(TreeNode node)
{
node.Nodes.Clear();
String fileNumber = node.Tag.ToString();
String sta3n = cbRegionSites.SelectedItem.ToString().Substring(1, 3);
SqlConnection cdw = new SqlConnection(ConfigurationManager.ConnectionStrings["CDW"].ConnectionString);
cdw.Open();
//SqlCommand cmd = new SqlCommand("SELECT VistaFieldNumber,VistaFieldName,MultipleFileNumber FROM CDWWork.Dim.VistaField WHERE Sta3n=" + sta3n + " AND VistaFileNumber='" + fileNumber + "' ORDER BY CAST(VistaFieldNumber As NUMERIC(30,10))", cdw);
SqlCommand cmd = new SqlCommand("SELECT VistaFieldNumber,VistaFieldName,MultipleFileNumber,FieldType,PointsToFileNumber,FieldLength FROM CDWWork.Dim.VistaField WHERE Sta3n=" + sta3n + " AND VistaFileNumber='" + fileNumber + "' ORDER BY CAST(VistaFieldNumber As NUMERIC(30,10))", cdw);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
//TreeNode field = new TreeNode(rdr["VistaFieldNumber"].ToString() + " - " + rdr["VistaFieldName"].ToString());
//TreeNode field = new TreeNode(rdr["VistaFieldNumber"].ToString() + " - " + rdr["VistaFieldName"].ToString() + " - " + rdr["FieldType"].ToString() + " - " + rdr["PointsToFileNumber"].ToString() + " - " + rdr["FieldLength"].ToString());
TreeNode field = new TreeNode(rdr["VistaFieldNumber"].ToString() + " - " + rdr["VistaFieldName"].ToString(), rdr["FieldType"].ToString(), rdr["PointsToFileNumber"].ToString(), rdr["FieldLength"].ToString());
field.Tag = rdr["VistaFieldNumber"].ToString();
if (rdr["MultipleFileNumber"].ToString().Length > 0)
{
field.Tag = rdr["MultipleFileNumber"].ToString();
field.Nodes.Add("RemoveNode");
}
node.Nodes.Add(field);
}
rdr.Close();
rdr.Dispose();
cmd.Dispose();
cdw.Close();
cdw.Dispose();
}

"Attempted to read or write protected memory" when filling a DataTable

I am developing some reports using ReportViewer and at certain point I have to connect to an Oracle database to retrieve some data and store it in a DataTable.
When the DataAdapter executes the Fill method I get this error:
"Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
Here's the code(unfortunatelly I can't put that sql code inside a procedure or something):
OleDbConnection objConn = new OleDbConnection(ConfigurationManager.ConnectionStrings["Premio"].ConnectionString);
OleDbCommand objCmd = new OleDbCommand();
DataTable objDt = new DataTable();
int vTipoTerr = LoadTipoTerritorio(ReportParameter.ReportData.Parameters.Item("pTerritorio").Value.ToString());
string vDataParametroDataFinal = ReportParameter.ReportData.Parameters.Item("pMesAnoCompetencia").Value.ToString();
int vDataInicial = int.Parse(vDataParametroDataFinal.Substring(0, 4));
vDataInicial = vDataInicial - 1;
vDataInicial = int.Parse(vDataInicial.ToString() + vDataParametroDataFinal.Substring(4, 2));
objCmd.CommandText = "SELECT T.Nome, " +
" T.Prontuario, " +
" C.Cobertura, " +
" Cn.Mesano_competencia, " +
" G.Grupo, " +
" T.Territorio, " +
" N.Negocio " +
" FROM Calculo C " +
" Inner Join Territorio T " +
" ON C.Id_Territorio = T.Id_Territorio " +
" Inner Join Grupo G " +
" ON C.Id_Grupo = G.Id_Grupo " +
" Inner Join Cenario Cn " +
" On Cn.Id_cenario = C.Id_cenario " +
" Inner Join Negocio N " +
" On Cn.Id_negocio = N.Id_negocio " +
" Where Cn.Mesano_competencia Between :p1 And :p2 --datas " +
" And G.Grupo = :p3 " +
" And Sub_terr(T.Territorio, Decode(:p4, 1, 'SETOR', 2, 'DISTRITO', 3, 'REGIONAL')) = :p5 " +
" And (Cn.Flag_cenario_disp = 1 Or Cn.Flag_cenario_disp_rec = 1) " +
" And N.Negocio = :p6 " +
" And Cn.Flag_recuperacao = 0 " +
" Order By Cn.Mesano_competencia; " +
"union all " +
"SELECT T.Nome, " +
" T.Prontuario, " +
" C.Cobertura, " +
" Cn.Mesano_competencia, " +
" G.Grupo, " +
" T.Territorio, " +
" N.Negocio " +
" FROM Calculo_Rec C " +
" Inner Join Territorio T " +
" ON C.Id_Territorio = T.Id_Territorio " +
" Inner Join Grupo G " +
" ON C.Id_Grupo = G.Id_Grupo " +
" Inner Join Cenario Cn " +
" On Cn.Id_cenario = C.Id_cenario " +
" Inner Join Negocio N " +
" On Cn.Id_negocio = N.Id_negocio " +
" Where Cn.Mesano_competencia Between :p1 And :p2 " +
" And G.Grupo = :p3 " +
" And Sub_terr(T.Territorio, Decode(:p4, 1, 'SETOR', 2, 'DISTRITO', 3, 'REGIONAL')) = :p5 " +
" And (Cn.Flag_cenario_disp = 1 Or Cn.Flag_cenario_disp_rec = 1) " +
" And N.Negocio = :p6 " +
" And Cn.Flag_recuperacao = 1 " +
" Order By Cn.Mesano_competencia ";
objCmd.Parameters.Add(new OleDbParameter("p1", OleDbType.Integer)).Value = vDataInicial;
objCmd.Parameters.Add(new OleDbParameter("p2", OleDbType.Integer)).Value = int.Parse(vDataParametroDataFinal);
objCmd.Parameters.Add(new OleDbParameter("p3", OleDbType.VarChar, 30)).Value = ReportParameter.ReportData.Parameters.Item("pGrupo").Value.ToString();
objCmd.Parameters.Add(new OleDbParameter("p4", OleDbType.Integer)).Value = vTipoTerr;
objCmd.Parameters.Add(new OleDbParameter("p5", OleDbType.VarChar, 30)).Value = ReportParameter.ReportData.Parameters.Item("pTerritorio").Value.ToString();
objCmd.Parameters.Add(new OleDbParameter("p6", OleDbType.VarChar, 30)).Value = ReportParameter.ReportData.Parameters.Item("pNegocio").Value.ToString();
OleDbDataAdapter objAdapter = new OleDbDataAdapter(objCmd);
objConn.Open();
objAdapter.Fill(objDt);
objConn.Close();
Thank you very much (:
Try using OracleCommand and OracleConnection objects instead:
OracleConnection objConn = new OracleConnection (ConfigurationManager.ConnectionStrings["Premio"].ConnectionString);
OracleCommand objCmd = new OracleCommand ();

Categories