Import from excel to sql format error - c#

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.

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.

There is no row at position 2 C# Runtime Exception

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)
{
}
}

Just In Time Loading (DataGridView) with Entity Framework

Heyya All,
I'm trying to implement Just in time loading into a Virtual Mode DataGridView (Winforms) but either im missing a big piece of the puzzle or its not working....
My table houses approx. 150k Records and takes about 2 minutes to load which is unacceptable.
Code Excerpt below
public partial class Customers : Form
{
private List<Database.Customer> store = new List<Database.Customer>();
public Customers()
{
InitializeComponent();
}
private void Customers_Load(object sender, EventArgs e)
{
store = Global.db.Customers.ToList();
dgv_data.VirtualMode = true;
BindingSource bs = new BindingSource();
bs.DataSource = Global.db.Customers.Local.ToBindingList();
dgv_data.DataSource = bs;
}
private void dgv_data_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
Global.db.SaveChanges();
}
void dgv_data_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
{
e.Value = store[e.RowIndex].GetType().GetProperties()[e.ColumnIndex].GetValue(store[e.RowIndex], null); ;
}
}
Now my understanding is that the CellValueNeeded pulls only the information the DataGridView can display from the database so 30 rows at a time reducing the load time to negligible durations
Can anyone shed some light on why its not working as expected?
The trick was to build a memory cache which displayed 100 or so rows at a time and update when other rows were required.
public partial class Customers : Form
{
private Cache memoryCache;
public Customers()
{
InitializeComponent();
}
private void Customers_Load(object sender, EventArgs e)
{
dgv_data.VirtualMode = true;
Load_Data();
}
private void Load_Data()
{
try
{
DataRetriever retriever =
new DataRetriever(Global.RetrieverCNS, "*Database Table Name*",null,true);
memoryCache = new Cache(retriever, 100);
foreach (DataColumn column in retriever.Columns)
{
dgv_data.Columns.Add(
column.ColumnName, column.ColumnName);
}
this.dgv_data.RowCount = retriever.RowCount;
}
catch (SqlException)
{
MessageBox.Show("Connection could not be established. " +
"Verify that the connection string is valid.");
Application.Exit();
}
}
void dgv_data_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
{
e.Value = memoryCache.RetrieveElement(e.RowIndex, e.ColumnIndex);
}
}
Data Cache Class (Copy and Paste)
public interface IDataPageRetriever
{
DataTable SupplyPageOfData(int lowerPageBoundary, int rowsPerPage);
}
public class DataRetriever : IDataPageRetriever
{
private string tableName;
private SqlCommand command;
public DataRetriever(string connectionString, string tableName,string sortby,bool desc)
{
if (sortby != null)
columnToSortBy = sortby;
sortdesc = desc;
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
command = connection.CreateCommand();
this.tableName = tableName;
}
private int rowCountValue = -1;
public int RowCount
{
get
{
// Return the existing value if it has already been determined.
if (rowCountValue != -1)
{
return rowCountValue;
}
// Retrieve the row count from the database.
command.CommandText = "SELECT COUNT(*) FROM " + tableName;
rowCountValue = (int)command.ExecuteScalar();
return rowCountValue;
}
}
private DataColumnCollection columnsValue;
public DataColumnCollection Columns
{
get
{
// Return the existing value if it has already been determined.
if (columnsValue != null)
{
return columnsValue;
}
// Retrieve the column information from the database.
command.CommandText = "SELECT * FROM " + tableName;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
adapter.FillSchema(table, SchemaType.Source);
columnsValue = table.Columns;
return columnsValue;
}
}
private string commaSeparatedListOfColumnNamesValue = null;
private string CommaSeparatedListOfColumnNames
{
get
{
// Return the existing value if it has already been determined.
if (commaSeparatedListOfColumnNamesValue != null)
{
return commaSeparatedListOfColumnNamesValue;
}
// Store a list of column names for use in the
// SupplyPageOfData method.
System.Text.StringBuilder commaSeparatedColumnNames =
new System.Text.StringBuilder();
bool firstColumn = true;
foreach (DataColumn column in Columns)
{
if (!firstColumn)
{
commaSeparatedColumnNames.Append(", ");
}
commaSeparatedColumnNames.Append("[" + column.ColumnName + "]");
firstColumn = false;
}
commaSeparatedListOfColumnNamesValue =
commaSeparatedColumnNames.ToString();
return commaSeparatedListOfColumnNamesValue;
}
}
// Declare variables to be reused by the SupplyPageOfData method.
private string columnToSortBy;
private bool sortdesc = false;
private SqlDataAdapter adapter = new SqlDataAdapter();
public DataTable SupplyPageOfData(int lowerPageBoundary, int rowsPerPage)
{
// Store the name of the ID column. This column must contain unique
// values so the SQL below will work properly.
if (columnToSortBy == null)
{
columnToSortBy = this.Columns[0].ColumnName;
}
if (!this.Columns[columnToSortBy].Unique)
{
throw new InvalidOperationException(String.Format(
"Column {0} must contain unique values.", columnToSortBy));
}
// Retrieve the specified number of rows from the database, starting
// with the row specified by the lowerPageBoundary parameter.
//DataTable Results = Global.db.Customers.Select<>
if (sortdesc == false)
command.CommandText = "Select Top " + rowsPerPage + " " +
CommaSeparatedListOfColumnNames + " From " + tableName +
" WHERE " + columnToSortBy + " NOT IN (SELECT TOP " +
lowerPageBoundary + " " + columnToSortBy + " From " +
tableName + " Order By " + columnToSortBy +
") Order By " + columnToSortBy;
else
{
command.CommandText = "Select Top " + rowsPerPage + " " +
CommaSeparatedListOfColumnNames + " From " + tableName +
" WHERE " + columnToSortBy + " NOT IN (SELECT TOP " +
lowerPageBoundary + " " + columnToSortBy + " From " +
tableName + " Order By " + columnToSortBy + " DESC" +
") Order By " + columnToSortBy + " DESC";
}
adapter.SelectCommand = command;
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
adapter.Fill(table);
return table;
}
}
public class Cache
{
private static int RowsPerPage;
// Represents one page of data.
public struct DataPage
{
public DataTable table;
private int lowestIndexValue;
private int highestIndexValue;
public DataPage(DataTable table, int rowIndex)
{
this.table = table;
lowestIndexValue = MapToLowerBoundary(rowIndex);
highestIndexValue = MapToUpperBoundary(rowIndex);
System.Diagnostics.Debug.Assert(lowestIndexValue >= 0);
System.Diagnostics.Debug.Assert(highestIndexValue >= 0);
}
public int LowestIndex
{
get
{
return lowestIndexValue;
}
}
public int HighestIndex
{
get
{
return highestIndexValue;
}
}
public static int MapToLowerBoundary(int rowIndex)
{
// Return the lowest index of a page containing the given index.
return (rowIndex / RowsPerPage) * RowsPerPage;
}
private static int MapToUpperBoundary(int rowIndex)
{
// Return the highest index of a page containing the given index.
return MapToLowerBoundary(rowIndex) + RowsPerPage - 1;
}
}
private DataPage[] cachePages;
private IDataPageRetriever dataSupply;
public Cache(IDataPageRetriever dataSupplier, int rowsPerPage)
{
dataSupply = dataSupplier;
Cache.RowsPerPage = rowsPerPage;
LoadFirstTwoPages();
}
// Sets the value of the element parameter if the value is in the cache.
private bool IfPageCached_ThenSetElement(int rowIndex,
int columnIndex, ref string element)
{
if (IsRowCachedInPage(0, rowIndex))
{
element = cachePages[0].table
.Rows[rowIndex % RowsPerPage][columnIndex].ToString();
return true;
}
else if (IsRowCachedInPage(1, rowIndex))
{
element = cachePages[1].table
.Rows[rowIndex % RowsPerPage][columnIndex].ToString();
return true;
}
return false;
}
public string RetrieveElement(int rowIndex, int columnIndex)
{
string element = null;
if (IfPageCached_ThenSetElement(rowIndex, columnIndex, ref element))
{
return element;
}
else
{
return RetrieveData_CacheIt_ThenReturnElement(
rowIndex, columnIndex);
}
}
private void LoadFirstTwoPages()
{
cachePages = new DataPage[]{
new DataPage(dataSupply.SupplyPageOfData(
DataPage.MapToLowerBoundary(0), RowsPerPage), 0),
new DataPage(dataSupply.SupplyPageOfData(
DataPage.MapToLowerBoundary(RowsPerPage),
RowsPerPage), RowsPerPage)};
}
private string RetrieveData_CacheIt_ThenReturnElement(
int rowIndex, int columnIndex)
{
// Retrieve a page worth of data containing the requested value.
DataTable table = dataSupply.SupplyPageOfData(
DataPage.MapToLowerBoundary(rowIndex), RowsPerPage);
// Replace the cached page furthest from the requested cell
// with a new page containing the newly retrieved data.
cachePages[GetIndexToUnusedPage(rowIndex)] = new DataPage(table, rowIndex);
return RetrieveElement(rowIndex, columnIndex);
}
// Returns the index of the cached page most distant from the given index
// and therefore least likely to be reused.
private int GetIndexToUnusedPage(int rowIndex)
{
if (rowIndex > cachePages[0].HighestIndex &&
rowIndex > cachePages[1].HighestIndex)
{
int offsetFromPage0 = rowIndex - cachePages[0].HighestIndex;
int offsetFromPage1 = rowIndex - cachePages[1].HighestIndex;
if (offsetFromPage0 < offsetFromPage1)
{
return 1;
}
return 0;
}
else
{
int offsetFromPage0 = cachePages[0].LowestIndex - rowIndex;
int offsetFromPage1 = cachePages[1].LowestIndex - rowIndex;
if (offsetFromPage0 < offsetFromPage1)
{
return 1;
}
return 0;
}
}
// Returns a value indicating whether the given row index is contained
// in the given DataPage.
private bool IsRowCachedInPage(int pageNumber, int rowIndex)
{
return rowIndex <= cachePages[pageNumber].HighestIndex &&
rowIndex >= cachePages[pageNumber].LowestIndex;
}

Displaying retrieved value in combobox

I am accesing value from database and displaying them on form ,i have successfully displayed retrived value in textbox and radiobox but i am not able to display them in combbox .
In combox items I have values(1 2 3 4) in this combox i want to display fetched value from database for eg. i accesed value 4 for combbox then it should display 4 value selected in it .
how could i achieve this?
public EditQuestionMaster(int qid_value)
{
InitializeComponent();
string columns = db.GetEditQuestions(qid_value);
string[] coldata=columns.Split('~');
txtQuestion.Text = coldata[1];
txtOption1.Text = coldata[2];
txtOption2.Text = coldata[3];
txtOption3.Text = coldata[4];
txtOption4.Text = coldata[5];
string a = coldata[6];
if (a == "1")
{
radioButton1.Checked = true;
}
else if (a == "2")
{
radioButton2.Checked = true;
}
else if (a == "3")
{
radioButton3.Checked = true;
}
else if (a == "4")
{
radioButton4.Checked = true;
}
cmbMarks.ValueMember = coldata[7];//in cmbMarks.ValueMember i am getting fetched value but it is not displaying in combbox ,where i am wrong?
}
GetEditQuestions(qid_value) Code
public string GetEditQuestions(int qid)
{
string data = "";
try
{
string sql = "select QID,Question,Opt1,Opt2,Opt3,Opt4,AnsOp,Marks from Questions where QID IN(" + qid + ") ";
cmd = new OleDbCommand(sql, acccon);
rs = cmd.ExecuteReader();
if (rs.Read())
{
data = rs[0].ToString() + "~" + rs[1].ToString() + "~" + rs[2].ToString() + "~" + rs[3].ToString() + "~" + rs[4].ToString() + "~" + rs[5].ToString() + "~" + rs[6].ToString() + "~" + rs[7].ToString() + "$";
}
}
catch (Exception err)
{
}
return data;
}
Thanks in Advance for any help
cmbMarks.Text = coldata[7].Substring(1)
See this MSDN page. The .Substring(1) is assuming that coldata[7] is a string with a $ as the first character.

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