There is no row at position 2 C# Runtime Exception - c#

I am retrieving data from db and displaying in Label. but the problem is that this cannot retrieve db tabel first row data. Its print Second row data. If i given the db first row c_code then it is given the Error "There is no row at position 2" Kindly please solve my problem.
Thanks you
private void Get_Purchasing_Amount()
{
try
{
string get_P_Amount = "";
double var_P_Amount = 0;
int var_C_Code = 0;
string query = "select c_code as 'code' from `db_vegetable`.`tbl_payment_master`";
DataTable dt_C_Code = method_Class.method_Class.FetchRecords(query);
if (dt_C_Code.Rows.Count > 0)
{
for (int i = 0; i <= dt_C_Code.Rows.Count; i++)
{
var_C_Code = Convert.ToInt32(dt_C_Code.Rows[i]["code"]);
if (var_C_Code.Equals(Convert.ToInt32(txt_Customer_Code.Text)))
{
if (check_All.Checked.Equals(true))
{
get_P_Amount = "SELECT IFNULL(`purchasing`,0) AS 'purchasing' FROM `db_vegetable`.`tbl_payment_master` WHERE `c_code` = " + txt_Customer_Code.Text + "";
}
else
{
string dt_Query = "select `id` as 'id' from `db_vegetable`.`tbl_order_details`";
DataTable dt_C_O = method_Class.method_Class.FetchRecords(dt_Query);
if (dt_C_O.Rows.Count > 0)
get_P_Amount = "SELECT IFNULL(SUM(t_price),0) as 'purchasing' FROM `db_vegetable`.`tbl_order_details` WHERE `c_code` = " + txt_Customer_Code.Text + " AND (`date` BETWEEN '" + txt_From_Date.Text + "' AND '" + txt_To_Date.Text + "')";
else
lbl_Purchasing_Amount.Text = "0";
}
DataTable dt = method_Class.method_Class.FetchRecords(get_P_Amount);
var_P_Amount = Convert.ToDouble(dt.Rows[0]["purchasing"]);
lbl_Purchasing_Amount.Text = var_P_Amount.ToString();
}
else
{
lbl_Purchasing_Amount.Text = "0";
}
}
}
else
{
lbl_Purchasing_Amount.Text = "0";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

I believe this is probably the issue:
for (int i = 0; i <= dt_C_Code.Rows.Count; ; i++) {...}
Please consider substituting foreach (DataRow row in dt_C_Code.Rows) { ...}
If it's important which row should logically come "first", then please consider using an order by clause in your SQL statement.

Now problem is solve the problem is that break key word.
private void Get_Purchasing_Amount()
{
try
{
string get_P_Amount = "";
double var_P_Amount = 0;
//int var_C_Code = 0;
string query = "select c_code as 'code' from `db_vegetable`.`tbl_payment_master`";
DataTable dt_C_Code = method_Class.method_Class.FetchRecords(query);
if (dt_C_Code.Rows.Count > 0)
{
for (int i = 0; i <= dt_C_Code.Rows.Count; i++)//these line generate error please check this
{
//var_C_Code = Convert.ToInt32(dt_C_Code.Rows[i]["code"]);
if (Convert.ToInt32(dt_C_Code.Rows[i]["code"]).Equals(Convert.ToInt32(txt_Customer_Code.Text)))
{
if (check_All.Checked.Equals(true))
{
get_P_Amount = "SELECT IFNULL(`purchasing`,0) AS 'purchasing' FROM `db_vegetable`.`tbl_payment_master` WHERE `c_code` = " + txt_Customer_Code.Text + "";
}
else
{
string dt_Query = "select `id` as 'id' from `db_vegetable`.`tbl_order_details`";
DataTable dt_C_O = method_Class.method_Class.FetchRecords(dt_Query);
if (dt_C_O.Rows.Count > 0)
get_P_Amount = "SELECT IFNULL(SUM(t_price),0) as 'purchasing' FROM `db_vegetable`.`tbl_order_details` WHERE `c_code` = " + txt_Customer_Code.Text + " AND (`date` BETWEEN '" + txt_From_Date.Text + "' AND '" + txt_To_Date.Text + "')";
else
lbl_Purchasing_Amount.Text = "0";
}
DataTable dt = method_Class.method_Class.FetchRecords(get_P_Amount);
var_P_Amount = Convert.ToDouble(dt.Rows[0]["purchasing"]);
lbl_Purchasing_Amount.Text = var_P_Amount.ToString();
break;
}
else
{
lbl_Purchasing_Amount.Text = "0";
}
}
}
else
{
lbl_Purchasing_Amount.Text = "0";
}
}
catch (Exception)
{
}
}

Related

Visual Studio Database Not Updating

I am working on a school project and for some reason my mysql database doesn't update despite no of row changed is more than 0 and triggering the Update sucessful alert. It also manage to only update my image data from my fileupload.
**admin_products_details_edit.aspx.cs**
protected void btn_ProdEdit_Click(object sender, EventArgs e)
{
int result = 0;
string image = "";
if (FileUpload_ProdImg.HasFile == true)
{
image = "images\\" + FileUpload_ProdImg.FileName;
img_result.ImageUrl = FileUpload_ProdImg.FileName;
}
else
{
image = img_result.ImageUrl;
}
Product Prod = new Product();
string datProdID = lbl_ProdID.Text;
string datProdName = tb_ProdName.Text;
string datProdDesc = tb_ProdDesc.Text;
string datProdImg = img_result.ImageUrl;
decimal datProdPrice = decimal.Parse(tb_ProdPrice.Text);
int datProdCal = int.Parse(tb_ProdCal.Text);
int datStockLvl = int.Parse(tb_StockLvl.Text);
result = Prod.ProductUpdate(datProdID, datProdName, datProdDesc, datProdImg, datProdPrice, datProdCal, datStockLvl);
if (result > 0)
{
string saveimg = Server.MapPath(" ") + "\\" + image;
FileUpload_ProdImg.SaveAs(saveimg);
Response.Write("<script>alert('Update successful');</script>");
Response.Redirect("admin_products_details.aspx?ProdID=" + datProdID);
}
else
{
Response.Write("<script>alert('Update fail');</script>");
}
}<-The code for the button edit event trigger
**Product.cs**
...public int ProductUpdate(string upID, string upName, string upDesc, string upImg, decimal upPrice, int upCal, int upstkLvl)
{
string queryStr = "UPDATE Products SET" + " ProdName = #productName, " + " ProdDesc = #productDesc, " + " ProdImg = #productImage, " + " ProdPrice = #productPrice, " + " ProdCalorie = #productCal, " + " StockLevel = #productStkLvl " + " WHERE ProdID = #productID";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#productID", upID);
cmd.Parameters.AddWithValue("#productName", upName);
cmd.Parameters.AddWithValue("#productDesc", upDesc);
cmd.Parameters.AddWithValue("#productImage", upImg);
cmd.Parameters.AddWithValue("#productPrice", upPrice);
cmd.Parameters.AddWithValue("#productCal", upCal);
cmd.Parameters.AddWithValue("#productStkLvl", upstkLvl);
conn.Open();
int nofRow = 0;
nofRow = cmd.ExecuteNonQuery();
conn.Close();
return nofRow;
}<-The code for updating the mysql database,located in a different cs file,titled Product.cs
My mysql database table is called Products
Thank you very much for your help in advance.

problem in multiple search criteria with dynamic sql and sql joins asp.net c# sql server

i have a search page with multiple search criteria and a different page show the search result. the problem i am facing is when two or more users(different pc or browser) search on that page the priviously searched results get affected by the newly searched result. basically the searched result of the privious user get replaced by the searched result of the last user when privious user click on paging or refresh the page. i have provided the code of the search page and search result page.
//code of the search criteria page
protected void btnRegularSrch_Click(object sender, EventArgs e)
{
string strCondition = string.Empty;
string strSql = string.Empty;
string custGender = string.Empty;
string custReli = string.Empty;
string custCaste = string.Empty;
string custMtonge = string.Empty;
string custCountry = string.Empty;
string custAge = string.Empty;
string custMstate = string.Empty;
strSql = "select * from tbl_CustomerInfo cust inner join tbl_Relig rel on rel.regid=cust.REGID inner join tbl_Locat loc on loc.regid=cust.REGID inner join tbl_Photos ph on ph.regid=cust.regid and cust.status=1 ";
//gender
if (Male.Checked)
{
custGender = "m";
}
else
{
custGender = "f";
}
strCondition += " where cust_gender='" + custGender + "'";
//age
if (drp_age_from.SelectedIndex > 0)
{
custAge = drp_age_from.SelectedItem.Text;
if (!string.IsNullOrEmpty(strCondition))
strCondition += "and cust.cust_age between '" + drp_age_from.SelectedItem.Text + "' and '" + drp_age_to.SelectedItem.Text + "'";
else
strCondition += "where cust.cust_age between '" + drp_age_from.SelectedItem.Text + "' and '" + drp_age_to.SelectedItem.Text + "'";
}
//religion
if (ddlSearchReli.SelectedIndex > 0)
{
custReli = ddlSearchReli.SelectedItem.Text;
if (!string.IsNullOrEmpty(strCondition))
strCondition += " and rel.Religion='" + custReli + "'";
else
strCondition += " where rel.Religion='" + custReli + "'";
}
//caste
if (DdlCaste2.SelectedIndex > 0)
{
custCaste = DdlCaste2.SelectedItem.Text;
if (!string.IsNullOrEmpty(strCondition))
strCondition += " and rel.Caste='" + custCaste + "'";
else
strCondition += " where rel.Caste='" + custCaste + "'";
}
//mothertonge
if (ddlCommunty.SelectedIndex > 0)
{
custMtonge = ddlCommunty.SelectedItem.Text;
if (!string.IsNullOrEmpty(strCondition))
strCondition += " and rel.MotherTongue='" + custMtonge + "'";
else
strCondition += " where rel.MotherTongue='" + custMtonge + "'";
}
//country
if (drp_country.SelectedIndex > 0)
{
custCountry = drp_country.SelectedItem.Text;
if (!string.IsNullOrEmpty(strCondition))
strCondition += " and loc.Country='" + custCountry + "'";
else
strCondition += " where loc.Country='" + custCountry + "'";
}
//marital status
if (ddlMStatus.SelectedIndex > 0)
{
strCondition = strCondition + " and (";
custMstate = ddlMStatus.SelectedItem.Text;
if (!string.IsNullOrEmpty(strCondition))
strCondition += " cust.maritalstatus='" + custMstate + "'";
else
strCondition += " where cust.maritalstatus='" + custMstate + "'";
//strCondition = strCondition.TrimEnd(MyChar);
strCondition = strCondition + ")";
}
strSql = strSql + strCondition;
Response.Redirect("SearchResult.aspx?condition=" + Server.UrlEncode(Encrypt(strSql)));
}
//code of the search result page
string conn = ConfigurationManager.ConnectionStrings["con_str"].ConnectionString;
Utility objUtil = new Utility();
static string Condition;
#region Private Properties
private int CurrentPage
{
get
{
object objPage = ViewState["_CurrentPage"];
int _CurrentPage = 0;
if (objPage == null)
{
_CurrentPage = 0;
}
else
{
_CurrentPage = (int)objPage;
}
return _CurrentPage;
}
set { ViewState["_CurrentPage"] = value; }
}
private int fistIndex
{
get
{
int _FirstIndex = 0;
if (ViewState["_FirstIndex"] == null)
{
_FirstIndex = 0;
}
else
{
_FirstIndex = Convert.ToInt32(ViewState["_FirstIndex"]);
}
return _FirstIndex;
}
set { ViewState["_FirstIndex"] = value; }
}
private int lastIndex
{
get
{
int _LastIndex = 0;
if (ViewState["_LastIndex"] == null)
{
_LastIndex = 0;
}
else
{
_LastIndex = Convert.ToInt32(ViewState["_LastIndex"]);
}
return _LastIndex;
}
set { ViewState["_LastIndex"] = value; }
}
#endregion
#region PagedDataSource
PagedDataSource _PageDataSource = new PagedDataSource();
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.QueryString["condition"] != null)
{
Condition = objUtil.Decrypt(Request.QueryString["condition"]);
this.BindItemsList();
}
}
}
protected DataTable getDataTable()
{
DataUtility objUtil = new DataUtility();
return objUtil.getDataTable(Condition);
//rptViewBasicInfo.DataSource = dt;
//rptViewBasicInfo.DataBind();
}
private void BindItemsList()
{
_PageDataSource.DataSource = this.getDataTable().DefaultView;
_PageDataSource.AllowPaging = true;
_PageDataSource.PageSize = 10;
_PageDataSource.CurrentPageIndex = CurrentPage;
ViewState["TotalPages"] = _PageDataSource.PageCount;
_PageDataSource.PageCount;
this.lbtnPrevious.Enabled = !_PageDataSource.IsFirstPage;
this.lbtnNext.Enabled = !_PageDataSource.IsLastPage;
Repeater1.DataSource = _PageDataSource;
Repeater1.DataBind();
this.doPaging();
}
private void doPaging()
{
DataTable dt = new DataTable();
dt.Columns.Add("PageIndex");
dt.Columns.Add("PageText");
fistIndex = CurrentPage - 5;
if (CurrentPage > 5)
{
lastIndex = CurrentPage + 5;
}
else
{
lastIndex = 10;
}
if (lastIndex > Convert.ToInt32(ViewState["TotalPages"]))
{
lastIndex = Convert.ToInt32(ViewState["TotalPages"]);
fistIndex = lastIndex - 10;
}
if (fistIndex < 0)
{
fistIndex = 0;
}
for (int i = fistIndex; i < lastIndex; i++)
{
DataRow dr = dt.NewRow();
dr[0] = i;
dr[1] = i + 1;
dt.Rows.Add(dr);
}
this.dlPaging.DataSource = dt;
this.dlPaging.DataBind();
}
//#endregion
protected void lbtnPrevious_Click(object sender, EventArgs e)
{
CurrentPage -= 1;
this.BindItemsList();
}
protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("Paging"))
{
CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
this.BindItemsList();
}
}
protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
{
LinkButton lnkbtnPage = (LinkButton)e.Item.FindControl("lnkbtnPaging");
if (lnkbtnPage.CommandArgument.ToString() == CurrentPage.ToString())
{
lnkbtnPage.Enabled = false;
lnkbtnPage.Style.Add("fone-size", "14px");
lnkbtnPage.Font.Bold = true;
}
}
protected void lbtnLast_Click(object sender, EventArgs e)
{
CurrentPage = (Convert.ToInt32(ViewState["TotalPages"]) - 1);
this.BindItemsList();
}
protected void lbtnFirst_Click(object sender, EventArgs e)
{
CurrentPage = 0;
this.BindItemsList();
}
protected void lbtnNext_Click(object sender, EventArgs e)
{
CurrentPage += 1;
this.BindItemsList();
}
On search result page, you declared the Condition variable to be static, so it behaves like a global variable and every time a user reached search result page, changes the value of Condition variable for all users.
Change this;
static string Condition;
To this;
string Condition;

3 DataGridViews interlinking issues

I am having three Datagridviews in my windows Form. One brings the data of Villages, on clicking any cell, Second Datagridview is populated with Customer Details. On clicking the customer name, third Datagridview must populate and calculate the balance of customer, whether credit is remaining or advance is deposited, now where I am facing problem is the third datagridview.
It specifically throws exception: Object reference set to null.
private void dataGridView3_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
double loansum1 = 0;
double emisum1 = 0;
double dd1 = 0;
double ei1 = 0;
double finalsum = 0;
foreach (DataGridViewRow drr1 in dataGridView3.Rows)
{
if (drr1.Cells[1].Selected == true)
{
string customerid = drr1.Cells[0].Value.ToString();
label1.Text = customerid;
SqlConnection setcon = new SqlConnection(ConfigurationManager.ConnectionStrings["sismanager"].ConnectionString);
using (SqlCommand getsup = new SqlCommand("SELECT Ciid, Cdate, Cparticulars, Ccr, Cdr FROM Customerbills WHERE Cid = #Cid ORDER BY Cdate DESC", setcon))
{
getsup.Parameters.AddWithValue("#Cid", customerid);
SqlDataAdapter drrr = new SqlDataAdapter(getsup);
try
{
setcon.Open();
DataTable data1 = new DataTable();
drrr.Fill(data1);
if (data1.Rows.Count > 0)
{
dataGridView1.DataSource = data1;
dataGridView1.Columns[0].HeaderText = "Bill Number";
dataGridView1.Columns[1].HeaderText = "Bill Date";
dataGridView1.Columns[2].HeaderText = "Particulars";
dataGridView1.Columns[3].HeaderText = "Credit Balance";
dataGridView1.Columns[4].HeaderText = "Cash Balance";
for (int ij = 0; ij < (dataGridView1.Rows.Count); ++ij)
{
dd1 = Double.Parse(dataGridView1.Rows[ij].Cells[3].Value.ToString());
ei1 = Double.Parse(dataGridView1.Rows[ij].Cells[4].Value.ToString());
loansum1 += dd1;
emisum1 += ei1;
}
label4.Text = (Math.Round(loansum1)).ToString();
label5.Text = (Math.Round(emisum1)).ToString();
finalsum = (emisum1 - loansum1);
if (finalsum >= 0)
{
label6.Text = "Rs. " + finalsum + " (Previous Amount Clear)";
}
else
{
label6.Text = "Rs. " + finalsum + " (Previous Amount Due)";
}
}
}
catch (SqlException exx)
{
}
finally
{
setcon.Close();
}
}
}
}
}
The exception error comes at:
dd1 = Double.Parse(dataGridView1.Rows[ij].Cells[3].Value.ToString());
Error Image below; It shows in call stack that the data is coming.

Import from excel to sql format error

hi I am trying to load data into sql from an excel spreadsheet from a web page, I am getting a "Cannot implicitly convert type 'string' to 'decimal" error I have tried different ways to correct this but nothing is working.
namespace CarpartsStore.Dealers
{
partial class DealerHome : System.Web.UI.Page
{
protected void ButtonUpload_Click(object sender, System.EventArgs e)
{
PanelUpload.Visible = true;
PanelView.Visible = false;
PanelImport.Visible = false;
}
protected OleDbCommand ExcelConnection()
{
// Connect to the Excel Spreadsheet
string xConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath("~/ExcelImport.xls") + ";" + "Extended Properties=Excel 8.0;";
// create your excel connection object using the connection string
OleDbConnection objXConn = new OleDbConnection(xConnStr);
objXConn.Open();
// use a SQL Select command to retrieve the data from the Excel Spreadsheet
// the "table name" is the name of the worksheet within the spreadsheet
// in this case, the worksheet name is "Members" and is coded as: [Members$]
OleDbCommand objCommand = new OleDbCommand("SELECT * FROM [Products$]", objXConn);
return objCommand;
}
protected void ButtonView_Click(object sender, System.EventArgs e)
{
PanelUpload.Visible = false;
PanelView.Visible = true;
PanelImport.Visible = false;
// Create a new Adapter
OleDbDataAdapter objDataAdapter = new OleDbDataAdapter();
// retrieve the Select command for the Spreadsheet
objDataAdapter.SelectCommand = ExcelConnection();
// Create a DataSet
DataSet objDataSet = new DataSet();
// Populate the DataSet with the spreadsheet worksheet data
objDataAdapter.Fill(objDataSet);
// Bind the data to the GridView
GridViewExcel.DataSource = objDataSet.Tables[0].DefaultView;
GridViewExcel.DataBind();
}
protected void ButtonImport_Click(object sender, System.EventArgs e)
{
PanelUpload.Visible = false;
PanelView.Visible = false;
PanelImport.Visible = true;
LabelImport.Text = "";
// reset to blank
// retrieve the Select Command for the worksheet data
OleDbCommand objCommand = new OleDbCommand();
objCommand = ExcelConnection();
// create a DataReader
OleDbDataReader reader;
reader = objCommand.ExecuteReader();
// create variables for the spreadsheet columns
int ProductID = 0;
int MakeID = 0;
int DealerID = 0;
string PartNumber = "";
string Description = "";
decimal UnitCost = 0.00M;
decimal Postage = 0.00M;
int QtyAvailable = 0;
string UserName = "";
string Make = "";
int counter = 0;
// used for testing your import in smaller increments
while (reader.Read())
{
counter = counter + 1;
// counter to exit early for testing...
// set default values for loop
ProductID = 0;
MakeID = 0;
DealerID = 0;
PartNumber = GetValueFromReader(reader,"PartNumber");
Description = GetValueFromReader(reader,"Description");
UnitCost = GetValueFromReader(reader,"UnitCost");
Postage = GetValueFromReader(reader, "Postage");
QtyAvailable = GetValueFromReader(reader,"QtyAvailable");
UserName = GetValueFromReader(reader,"UserName");
Make = GetValueFromReader(reader,"Make");
// Insert any required validations here...
MakeID = GetMakeID(Make);
DealerID = GetDealerID(UserName);
//retrieve the MakeID
ProductID = ImportIntoProducts(PartNumber, Description, UnitCost, Postage, QtyAvailable, MakeID, DealerID);
LabelImport.Text = LabelImport.Text + ProductID + PartNumber + " " + Description + " " + UnitCost + " " + Postage + " " + QtyAvailable + " " + UserName + " Make_id: " + MakeID + " " + Make + "<br>";
//If counter > 2 Then ' exit early for testing, comment later...
// Exit While
//End If
}
reader.Close();
}
protected string GetValueFromReader(OleDbDataReader myreader, string stringValue)
{
object val = myreader[stringValue];
if (val != DBNull.Value)
return val.ToString();
else
return "";
}
protected void ButtonUploadFile_Click(object sender, System.EventArgs e)
{
if (FileUploadExcel.HasFile)
{
try
{
// alter path for your project
FileUploadExcel.SaveAs(Server.MapPath("~/ExcelImport.xls"));
LabelUpload.Text = "Upload File Name: " +
FileUploadExcel.PostedFile.FileName + "<br>" +
"Type: " + FileUploadExcel.PostedFile.ContentType +
" File Size: " + FileUploadExcel.PostedFile.ContentLength +
" kb<br>";
}
catch (System.NullReferenceException ex)
{
LabelUpload.Text = "Error: " + ex.Message;
}
}
else
{
LabelUpload.Text = "Please select a file to upload.";
}
}
protected int GetMakeID(string MakeName)
{
int makeID = 0;
try
{
CarpartsStore.DataSets.SSSProductsDataSetTableAdapters.MakesTableAdapter SSAdapter = new CarpartsStore.DataSets.SSSProductsDataSetTableAdapters.MakesTableAdapter();
SSSProductsDataSet.MakesDataTable SSDataTable = null;
SSDataTable = SSAdapter.GetMakeByName(MakeName);
// see if the category already exists in the table, if not insert it
if (SSDataTable != null)
{
if (SSDataTable.Rows.Count > 0)
{
if (SSDataTable[0].MakeID > 0)
{
makeID = SSDataTable[0].MakeID;
}
}
}
if (makeID == 0)
{
// if it is still 0, then insert it into the table
// retrieve the identity key category_id from the insert
makeID = (int)SSAdapter.InsertMakeQuery(MakeName);
// if this fails to return the proper category_id, make sure to
// set the InsertCategoryQuery ExecuteMode Property to Scalar
}
return makeID;
}
catch (System.NullReferenceException ex)
{
LabelImport.Text = LabelImport.Text + ex.Message;
return 0;
}
}
protected int GetDealerID(string UserName)
{
int DealerID = 0;
try
{
CarpartsStore.DataSets.SSSProductsDataSetTableAdapters.DealersTableAdapter SSAdapter = new CarpartsStore.DataSets.SSSProductsDataSetTableAdapters.DealersTableAdapter();
SSSProductsDataSet.DealersDataTable SSDataTable = null;
SSDataTable = SSAdapter.GetDealersByUserName(UserName);
// see if the User already exists in the table, if not insert it
if (SSDataTable != null)
{
if (SSDataTable.Rows.Count > 0)
{
if (SSDataTable[0].DealerID > 0)
{
DealerID = SSDataTable[0].DealerID;
}
}
}
if (DealerID == 0)
{
// if it is still 0, then insert it into the table
// retrieve the identity key category_id from the insert
DealerID = 0;
// if this fails to return the proper category_id, make sure to
// set the InsertCategoryQuery ExecuteMode Property to Scalar
}
return DealerID;
}
catch (System.NullReferenceException ex)
{
LabelImport.Text = LabelImport.Text + ex.Message;
return 0;
}
}
protected int ImportIntoProducts(string PartNumber, string Description, decimal UnitCost, decimal Postage, int QtyAvailable, int MakeID, int DealerID)
{
// make sure values don't exceed column limits
PartNumber = Left(PartNumber, 50);
Description = Left(Description, 300);
UnitCost = Convert.ToDecimal(UnitCost);
int ProductID = 0;
try
{
CarpartsStore.DataSets.SSSProductsDataSetTableAdapters.ProductsTableAdapter SSAdapter = new CarpartsStore.DataSets.SSSProductsDataSetTableAdapters.ProductsTableAdapter();
SSSProductsDataSet.ProductsDataTable SSDataTable = null;
SSDataTable = SSAdapter.GetProductsByPartNumberDealer(PartNumber, DealerID);
// see if the category already exists in the table, if not insert it
if (SSDataTable != null)
{
if (SSDataTable.Rows.Count > 0)
{
if (SSDataTable[0].ProductID > 0)
{
ProductID = SSDataTable[0].ProductID;
LabelImport.Text = LabelImport.Text + "<font color=blue>PartNumber Found, Not Imported: " + " ID: " + ProductID + " " + PartNumber + " " + Description + "" + UnitCost + "" + Postage + ".</font><br>";
}
}
}
if (ProductID == 0)
{
// if it is still 0, then insert it into the table
// retrieve the identity key ProductID from the insert
ProductID = Convert.ToInt32(SSAdapter.InsertProductQuery(PartNumber, Description,UnitCost, Postage, QtyAvailable, MakeID, DealerID));
LabelImport.Text = LabelImport.Text + "<font color=white>Part Number Imported: " + " ID: " + ProductID + " " + PartNumber + " " + Description + " Cost: " + UnitCost + ".</font><br>";
}
return ProductID;
}
catch (System.NullReferenceException ex)
{
LabelImport.Text = LabelImport.Text + "<font color=red>" + ex.Message + "</font><br>";
return 0;
}
}
// http://www.mgbrown.com/PermaLink68.aspx
public static string Left(string text, int length)
{
if (length < 0)
throw new ArgumentOutOfRangeException("length", length, "length must be > 0");
else if (length == 0 || text.Length == 0)
return "";
else if (text.Length <= length)
return text;
else
return text.Substring(0, length);
}
}
}
The following code change will allow your code to run:
try
{
UnitCost = GetValueFromReader(reader,"UnitCost");
}
catch(Exception)
{
// put a breakpoint here to find the problem using the debugger
}
try
{
Postage = GetValueFromReader(reader, "Postage");
}
catch(Exception)
{
// put a breakpoint here to find the problem using the debugger
}
What you really want to do is understand how the source data is causing the error. (Maybe you have a null or a non-numeric value in the source data.)
Leaving the code like this could (and probably will) introduce data errors into other parts of your system.

The given value of type DateTime from the data source cannot be converted to type decimal of the spe

I am trying to migrate data from Oracle to SQL.
I already created Table name and field Name.
Type and Size are same on both: e.g.
at Oracle Varchar2(11), On SQL VARCHAR(11)
at Oracle Date, On SQL datetime2(0).
In my application I'm using SqlBulkCopy function. But I face the above error on Date filed.
private void Processing(string sPath)
{
string AppPath = Application.StartupPath.ToString();
IniFile myIni = new IniFile(sPath);
string allTable = myIni.IniReadValue("TABLENAME", "TABLE");
string[] alltables = allTable.Split(',');
foreach (var tableName in alltables)
{
string whereSqlQuery = string.Empty;
string sOrderBySqlQuery = string.Empty;
string sSQLSelect = string.Empty;
string sRCount = string.Empty;
whereSqlQuery = myIni.IniReadValue(tableName, "WHERE");
TableName = tableName;
sOrderBySqlQuery = myIni.IniReadValue(tableName, "ORDERBY");
sSQLSelect = myIni.IniReadValue(tableName, "SQLSELECT");
//sRCount = myIni.IniReadValue(tableName, "RCOUNT");
if (radAuto.Checked == true)
ConnectAndQuery(tableName, whereSqlQuery, sOrderBySqlQuery, sSQLSelect, sRCount);
else
ConnectAndQuery(tableName, whereSqlQuery, sOrderBySqlQuery);
}
}
private void ConnectAndQuery(string strTableName, string strWhere, string strOrderBy, string sSqlSelect, string sRcount)
{
Cursor.Current = Cursors.WaitCursor;
string connectionString = GetConnectionString();
// Using
OracleConnection connection = new OracleConnection();
SqlConnection oConn = default(SqlConnection);
DataTable dtSQL = null;
DateTime dtLog = DateTime.Now;
try
{
//Opening Oracle DB Connection
connection.ConnectionString = connectionString;
connection.Open();
ShownLog(string.Format("Table = {0} , -- STARTING --", strTableName));
ShownLog("Oracle Connection Opened, OK");
OracleCommand command = connection.CreateCommand();
if (!string.IsNullOrEmpty(strWhere))
SqlQuery = "SELECT * FROM " + strTableName + " WHERE "+ strWhere;
else
SqlQuery = string.Format("SELECT * FROM {0} ", strTableName);
if (!string.IsNullOrEmpty(strOrderBy))
SqlQuery += " ORDER BY " + strOrderBy;
command.CommandText = SqlQuery;
System.DateTime startTime = System.DateTime.Now;
ShownLog("Starting Date Time : " + startTime);
DataTable dtTotalInsertCount = new DataTable(strTableName);
if (!string.IsNullOrEmpty(sRcount))
{
//OracleDataAdapter adpCount = new OracleDataAdapter(sRcount, connectionString);
////adpCount.FillSchema(dtTotalInsertCount, SchemaType.Source);
//adpCount.Fill(dtTotalInsertCount);
}
OracleDataAdapter adapter = new OracleDataAdapter(SqlQuery, connectionString);
DataTable dt = new DataTable(strTableName);
adapter.FillSchema(dt, SchemaType.Source);
bool valid = true;
bool bCheck = true;
int count = 1000;
int start = 0;
string sLogQuery = SqlQuery.Replace("'", "");
dtLog = DateTime.Now;
//Insert to SQL Log Table
Insert(strTableName, dtLog, sLogQuery);
int iLogCount = 0;
int iActualCount = 0;
do
{
int iEnd = 0;
adapter.Fill(start, count, dt);
valid = dt.Rows.Count > 0 ? true : false;
if (valid)
{
iLogCount += dt.Rows.Count;
iEnd = start + dt.Rows.Count;
ShownLog("No of data Rows retrieved from Oracle, Count = " + dt.Rows.Count);
//Create the SQL Server Table
oConn = new SqlConnection(txtDestinationConnString.Text);
oConn.Open();
ShownLog("SQL Connection Opened, OK");
if (string.IsNullOrEmpty(sSqlSelect))
bCheck = false;
if (bCheck)
{
ShownLog("Data Comparision Start : " + System.DateTime.Now);
//If SQL Select Statement has
if (!string.IsNullOrEmpty(sSqlSelect))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = sSqlSelect;
cmd.Connection = oConn;
cmd.CommandType = CommandType.Text;
SqlDataReader reader = cmd.ExecuteReader();
dtSQL = new DataTable();
dtSQL.Load(reader);
cmd = null;
reader = null;
//Return record has more than 0
ShownLog("Start Duplicate Checking : " + System.DateTime.Now);
if (dtSQL.Rows.Count > 0)
{
foreach (DataRow dr in dtSQL.Rows)
{
DataRow[] result;
if (strTableName == "ITK_STAFF" || strTableName == "ITK_FLIGHT")
{
result = dt.Select("URNO='" + dr[0].ToString() + "'");
}
else
result = dt.Select("URNO=" + dr[0]);
if (result.Length > 0)
{
foreach (var drRemove in result)
{
dt.Rows.Remove(drRemove);
}
}
}
}
ShownLog("End Duplicate Checking : " + System.DateTime.Now);
}
ShownLog("Actual No.s of records to insert : " + dt.Rows.Count);
if (dt.Rows.Count == count)
bCheck = false;
ShownLog("Data Comparision End : " + System.DateTime.Now);
}
if (valid)
{
ShownLog(System.DateTime.Now + " Copying " + strTableName + " From : " + start.ToString() + " To : " + iEnd);
}
start += count;
if (dt.Rows.Count > 0)
{
iActualCount += dt.Rows.Count;
CopyData(dt, oConn);
dt.Rows.Clear();
}
oConn.Close();
oConn = null;
}
} while (valid);
System.DateTime endTime = System.DateTime.Now;
ShownLog("Ending DateTime: " + endTime);
//msgOut("No of rows copied from oracle to SQL Server , Count = " + dt.Rows.Count);
TimeSpan diffTime = endTime.Subtract(startTime);
ShownLog(String.Format("Time Difference is Days : {0}, Hours : {1}, Minites : {2}, seconds : {3} ,Milliseconds : {4}", diffTime.Days, diffTime.Hours, diffTime.Minutes, diffTime.Seconds, diffTime.Milliseconds));
ShownLog(string.Format("Table = {0} , -- FINISHED --", strTableName));
ShownLog(string.Empty);
Update(iLogCount, iActualCount, strTableName, dtLog, sLogQuery, " ", true);
Cursor.Current = Cursors.Default;
}
catch (Exception ex)
{
Cursor.Current = Cursors.Default;
ShownLog(ex.ToString());
ShownLog(string.Empty);
Update(0, 0, strTableName, dtLog, "", ex.ToString(), false);
((IDisposable)connection).Dispose();
if (oConn != null)
oConn.Close();
RadioButtonControl();
}
finally
{
Cursor.Current = Cursors.Default;
((IDisposable)connection).Dispose();
if (oConn != null)
oConn.Close();
RadioButtonControl();
}
}
private void CopyData(DataTable sourceTable, SqlConnection destConnection)
{
// Using
SqlBulkCopy s = new SqlBulkCopy(destConnection);
try
{
s.DestinationTableName = TableName;
s.NotifyAfter = 10000;
s.SqlRowsCopied += new SqlRowsCopiedEventHandler(s_SqlRowsCopied);
s.WriteToServer(sourceTable);
s.Close();
}
finally
{
((IDisposable)s).Dispose();
}
}

Categories