Related
Error Returned:
"No value given for one or more required parameters."
String Array to pass to function:
String[,] arrParams = new String[1, 2] {
{"#ToUpper_user_id", id}
};
Value of id:
"test" (without the quotes)
SQL:
strSQL = "select * from users where ToUpper_user_id = ?;";
SQL Function Call:
if (jdb.getdb_data(strSQL, arrParams, strTableName, out dsGet, out strTechMessage))
{
...
}
Function that calls to get data from the db:
public static bool getdb_data(String strSQL, String[,] arrParams, String strTableName, out DataSet dsGet, out String strTechMessage)
{
bool boolRC = true;
String key = String.Empty;
String val = String.Empty;
dsGet = new DataSet();
strTechMessage = String.Empty;
String strSQL_Empty = String.Empty;
string connectionString = jdb.getConnString();
using (OleDbConnection connection =
new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(strSQL, connection);
if (arrParams.GetLength(0) > 0)
{
for (int i = 0; i < arrParams.GetLength(0); i++)
{
for (int j = 0; j < arrParams.GetLength(1); j++)
{
if (j.Equals(0)) { key = arrParams[i, j]; }
if (j.Equals(1)) { val = arrParams[i, j]; }
}
command.Parameters.AddWithValue(key, val);
}
}
else
{
boolRC = false;
strTechMessage = "No parameters found";
}
// Open the connection in a try/catch block.
// Create and execute the DataReader, writing the result
// set to the console window.
if (boolRC)
{
try
{
connection.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(strSQL, connection);
adapter.Fill(dsGet, strTableName);
}
catch (Exception ex)
{
boolRC = false;
strTechMessage = ex.Message;
}
}
}
return boolRC;
}
Please help - I think I am goin' insane! (The Update CRUD all works with parameters . . . just the select code is giving me the error.)
In "get_dbdata(...)" above, I should have have had:
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
instead of:
OleDbDataAdapter adapter = new OleDbDataAdapter(strSQL, connection);
In the code, both the sql and parameters have already been added to the command above.
Works now!
im working on a project in mvc4 visual studio and have add an Uploadhandler.ashx.cs to upload the files.
the code is working to upload the files and insert into the information into my database.
Now what i try/need:
i have add a column where i want insert a number of each row like 1, 2 ,3, 4 etc...
in my code i have a for loop to do what i want for each file.
How can i generate a variable which add automatically +1 to insert it into my database.
i have try a lot of things like:
var a=1;
for(.......)
{
/*******My code****************/
a=a+1;
}
Hope that someone can give a hand with this:
here is my code:
private void UploadWholeFile(HttpContext context, List<FilesStatus> statuses)
{
using (SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
var a= 1;
for (int i = 0; i < context.Request.Files.Count; i++)
{
var file = context.Request.Files[i];
var fullpath = "/Files/" + Path.GetFileName(file.FileName);
var myfilename=Path.GetFileName(file.FileName);
file.SaveAs(fullpath);
statuses.Add(new FilesStatus(fullName, file.ContentLength, fullpath
string sql1 = "insert into Image(FileName, Number) values (#FileName, #Number)";
using (SqlCommand cmd = new SqlCommand(sql1, cn))
{
cmd.Parameters.AddWithValue("#FileName", myfilename);
cmd.Parameters.AddWithValue("#Number", a);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
a = a + 1;
}
}
}
Why don't you just use your iteration variable, i?
Your pasted code has some errors, here is fixed code. (corrections are marked with ).
private void UploadWholeFile(HttpContext context, List<FilesStatus> statuses)
{
using (SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
var a= 1;
**cn.Open();**
for (int i = 0; i < context.Request.Files.Count; i++)
{
var file = context.Request.Files[i];
var fullpath = "/Files/" + Path.GetFileName(file.FileName)
file.SaveAs(fullpath);
**statuses.Add(new FilesStatus(fullName, file.ContentLength, fullpath));**
**string sql1 = "insert into Imagem(FileName, Number, Id_Magazine, Tem_Conteudo) values (#FileName, #Number, #Id_Magazine, #Tem_Conteudo)";**
using (SqlCommand cmd = new SqlCommand(sql1, cn))
{
cmd.Parameters.AddWithValue("#NomeFicheiro", myfilename);
cmd.Parameters.AddWithValue("#Id_Magazine", context.Request.Form["MagazineId"]);
cmd.Parameters.AddWithValue("#Tem_Conteudo", false);
cmd.Parameters.AddWithValue("#Number", a++);
**cmd.ExecuteNonQuery();**
}
}
**cn.Close();**
}
}
Hope it helps!
Regards,
Uroš
Try declaring the variable as an int, and you can use a++ to increment a by 1:
int a=1;
for(.......)
{
/*******My code****************/
a++;
}
Also, you have declared an integer i in your for loop that increments by 1 each time the loop is run, so you could use this instead of declaring a:
for (int i = 0; i < context.Request.Files.Count; i++)
{
...
cmd.Parameters.AddWithValue("#Number", i);
...
}
Finally, I'm not sure why you need this column in your database at all. If you are using it as a unique identifier the make it the Primary Key. You can then set this to auto-increment without needing to add the value each time.
I am trying to save some values to data table in MS SQL , but i have some problem with the Data types . i need to use Parameters to convert those values to proper data types
this is my table ,,,
Table image
this is the code that i'm using to pass values to the database ,, i need to use Parameters to convert data, please help me to do it ...
private void InsertRec(StringCollection sc)
{
var conn = new SqlConnection(GetConnectionString());
var sb = new StringBuilder(string.Empty);
var splitItems = (string[])null;
foreach (string item in sc)
{
const string sqlStatement =
"INSERT INTO DEL_PurchasesLines1 (DealerCode,InvoiceNo,InvoiceDate,ItemIdentityCode,PurchasingPrice,DiscountRate,Discount,IssueMode,Qty,Total,ExpireDate,BatchNumber,UploadedStatus,InsertedDate,UploadedDate,Force,Principle,NewTotal) VALUES";
if (item.Contains(","))
{
splitItems = item.Split(",".ToCharArray());
sb.AppendFormat("{0}('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}','{17}','{18}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2], splitItems[3], splitItems[4], splitItems[5], splitItems[6], splitItems[7], splitItems[8], splitItems[9], splitItems[10], splitItems[11], splitItems[12], splitItems[13], splitItems[14], splitItems[15], splitItems[16], splitItems[17]);
}
}
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sb.ToString(), conn) { CommandType = CommandType.Text };
cmd.ExecuteNonQuery();
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
this is how i take the values in to query.
protected void btnSaave_Click(object sender, EventArgs e)
{
int rowIndex = 0;
StringCollection sc = new StringCollection();
if (ViewState["CurrentData"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentData"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
var dtDealerCode = txtIDealerCode.Text;
var dtInvoiceNo = txtInvoiceNumber.Text;
var dtInvoiceDate = txtInvoiceDate.Text;
var dtItemIdentityCode = (Label)GridView1.Rows[rowIndex].Cells[1].FindControl("ItemCode");
var dtPurchasingPrice = (Label)GridView1.Rows[rowIndex].Cells[3].FindControl("UnitPrice");
var dtDiscountRate = txtDiscount.Text;
var dtDiscount = txtProductDiscount.Text;
var dtIssueMode = ddlIssueMode.SelectedValue;
var dtQty = (Label)GridView1.Rows[rowIndex].Cells[6].FindControl("Quantity");
var dtTotal = (Label)GridView1.FooterRow.FindControl("GetTotal");
var dtExpireDate = (Label)GridView1.Rows[rowIndex].Cells[5].FindControl("ExpiaryDate");
var dtBatchNumber = (Label)GridView1.Rows[rowIndex].Cells[4].FindControl("Batch");
var dtUploadedStatus = txtInvoiceDate.Text;
var dtInsertedDate = "1";
var dtUploadedDate = txtInvoiceDate.Text;
var dtForce = txtForce.Text;
var dtPrinciple = txtPrinciple.Text;
var NewTotal = (Label)GridView1.FooterRow.FindControl("GetQuantity");
sc.Add(dtDealerCode + "," + dtInvoiceNo + "," + dtInvoiceDate + "," + dtItemIdentityCode.Text + "," + dtPurchasingPrice.Text + "," + dtDiscountRate + "," + dtDiscount + "," + dtIssueMode + "," + dtQty.Text + "," + dtTotal.Text + "," + dtExpireDate + "," + dtBatchNumber.Text + "," + dtUploadedStatus + "," + dtInsertedDate + "," + dtUploadedDate + "," + dtForce + "," + dtPrinciple + "," + dtPrinciple + "," + NewTotal.Text);
rowIndex++;
}
InsertRec(sc);
}
}
}
The correct way is to build a method that asks for the specific values it expects, either by having an parameter for each item or via a class type, ie either this:
private void InsertRec(DEL_PurchasesLines1 lineToInsert)
where DEL_PurchasesLines1 is a class you will create (named after the table), or this:
private void InsertRec(string DealerCode,string InvoiceNo,DateTime InvoiceDate,
string ItemIdentityCode,decimal PurchasingPrice, decimal DiscountRate,
decimal Discount,string IssueMode,decimal Qty,decimal Total,
DateTime ExpireDate,string BatchNumber,string UploadedStatus,
string InsertedDate,DateTime UploadedDate,string Force,
decimal Principle,decimal NewTotal)
FWIW, that many columns in a single table almost always means something is wrong with the table design, but I'll leave that alone for now. Going with the second method, your button click would look like this:
protected void btnSave_Click(object sender, EventArgs e)
{
if (ViewState["CurrentData"] == null) return;
DataTable dtCurrentTable = (DataTable)ViewState["CurrentData"];
if (dtCurrentTable.Rows.Count == 0) return;
int rowIndex = 0;
var dtDealerCode = txtIDealerCode.Text;
var dtInvoiceNo = txtInvoiceNumber.Text;
var dtInvoiceDate = DateTime.Parse(txtInvoiceDate.Text);
var dtDiscountRate = decimal.Parse(txtDiscount.Text);
var dtDiscount = decimal.Parse(txtProductDiscount.Text);
var dtIssueMode = ddlIssueMode.SelectedValue;
var dtUploadedStatus = DateTime.Parse(txtInvoiceDate.Text);
var dtInsertedDate = "1"; //Really?
var dtUploadedDate = DateTime.Parse(txtInvoiceDate.Text);
var dtForce = txtForce.Text;
var dtPrinciple = decimal.Parse(txtPrinciple.Text);
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
var dtItemIdentityCode = (Label)GridView1.Rows[rowIndex].Cells[1].FindControl("ItemCode");
var dtPurchasingPrice = decimal.Parse((Label)GridView1.Rows[rowIndex].Cells[3].FindControl("UnitPrice"));
var dtQty = decimal.Parse((Label)GridView1.Rows[rowIndex].Cells[6].FindControl("Quantity"));
var dtTotal = decimal.Parse((Label)GridView1.FooterRow.FindControl("GetTotal"));
var dtExpireDate = DateTime.Parse((Label)GridView1.Rows[rowIndex].Cells[5].FindControl("ExpiaryDate"));
var dtBatchNumber = (Label)GridView1.Rows[rowIndex].Cells[4].FindControl("Batch");
var NewTotal = decimal.Parse((Label)GridView1.FooterRow.FindControl("GetQuantity"));
InsertRec(dtDealerCode,dtInvoiceNo,dtInvoiceDate,dtItemIdentityCode,
dtPurchasingPrice,dtDiscountRate,dtDiscount,dtIssueMode,dtQty,
dtTotal,dtExpireDate,dtBatchNumber,dtUploadedStatus,dtInsertedDate,
dtUploadedDate,dtForce,dtPrinciple,NewTotal);
rowIndex++;
}
}
To bring it all together, InsertRec() will look like this:
private void InsertRec(string DealerCode,string InvoiceNo,DateTime InvoiceDate,
string ItemIdentityCode,decimal PurchasingPrice, decimal DiscountRate,
decimal Discount,string IssueMode,decimal Qty,decimal Total,
DateTime ExpireDate,string BatchNumber,string UploadedStatus,
string InsertedDate,DateTime UploadedDate,string Force,
decimal Principle,decimal NewTotal)
{
const string sqlStatement =
"INSERT INTO DEL_PurchasesLines1 (" +
"DealerCode,InvoiceNo,InvoiceDate,ItemIdentityCode,PurchasingPrice,DiscountRate,Discount,IssueMode,Qty,Total,ExpireDate,BatchNumber,UploadedStatus,InsertedDate,UploadedDate,Force,Principle,NewTotal" +
") VALUES (" +
"#DealerCode, #InvoiceNo, #InvoiceDate, #ItemIdentityCode, #PurchasingPrice, #DiscountRate, #Discount, #IssueMode, #Qty, #Total, #ExpireDate, #BatchNumber, #UploadSTatus, #InsertedDate, #UploadedDate, #Force, #Principle, #NewTotal" +
")";
using (conn = new SqlConnection(GetConnectionString())
using (cmd = new SqlCommand(sqlStatement, conn))
{
cmd.Parameters.Add("#DealerCode", SqlDbType.NVarChar, 10).Value = DealerCode;
cmd.Parameters.Add("#InvoiceNo", SqlDbType.NVarChar, 10).Value = InvoiceNo;
cmd.Parameters.Add("#InvoiceDate", SqlDbType.DateTime).Value = InvoiceDate;
cmd.Parameters.Add("#ItemIdentityCode", SqlDbType.NVarChar, 10).Value = ItemIdentityCode;
cmd.Parameters.Add("#PurchasingPrice", SqlDbType.Decimal).Value = PurchasingPrice;
cmd.Parameters.Add("#DiscountRate", SqlDbType.Decimal).Value = DiscountRate;
//...
conn.Open();
cmd.ExecuteNonQuery();
}
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
}
What you were doing with the StringBuilder and Format strings there was totally inappropriate, thanks to a little thing called Sql Injection. It's kind of important, so you should definitely do some reading about it.
I also see that you're trying to group the inserts into a single batch. That's nice, but thanks to connection pooling it doesn't really get you much. It's also harder to do with correct query parameterization. It's not impossible, though, so I'll show you an example now using the other method signature, which makes it a bit easier:
private void InsertRec(DEL_PurchasesLines1[] linesToInsert)
{
const string sqlBase =
"INSERT INTO DEL_PurchasesLines1 (" +
"(DealerCode,InvoiceNo,InvoiceDate,ItemIdentityCode,PurchasingPrice,DiscountRate,Discount,IssueMode,Qty,Total,ExpireDate,BatchNumber,UploadedStatus,InsertedDate,UploadedDate,Force,Principle,NewTotal)" +
" VALUES ";
const string valueBase =
"{0}(#DealerCode{1}, #InvoiceNo{1}, #InvoiceDate{1}, #ItemIdentityCode{1}, #PurchasingPrice{1}, #DiscountRate{1}, #Discount{1}, #IssueMode{1}, #Qty{1}, #Total{1}, #ExpireDate{1}, #BatchNumber{1}, #UploadSTatus{1}, #InsertedDate{1}, #UploadedDate{1}, #Force{1}, #Principle{1}, #NewTotal{1})";
var sb = new StringBuilder(sqlBase);
if (DEL_PurchasesLines1.Length > 1) sb.Append("(")
var delimiter = "";
for (int i = 0;i<DEL_PurchasesLines1.Length;i++)
{
sb.AppendFormat(valueBase, i, delimiter);
delimiter = ",";
}
if (DEL_PurchasesLines1.Length > 1) sb.Append(")")
using (conn = new SqlConnection(GetConnectionString())
using (cmd = new SqlCommand(sqlStatement, conn))
{
for (int i = 0;i<DEL_PurchasesLines1.Length;i++)
{
cmd.Parameters.Add("#DealerCode" + i, SqlDbType.NVarChar, 10).Value = linesToInsert[i].DealerCode;
cmd.Parameters.Add("#InvoiceNo" + i, SqlDbType.NVarChar, 10).Value = linesToInsert[i].InvoiceNo;
cmd.Parameters.Add("#InvoiceDate + i", SqlDbType.DateTime).Value = linesToInsert[i].InvoiceDate;
cmd.Parameters.Add("#ItemIdentityCode" + i, SqlDbType.NVarChar, 10).Value = linesToInsert[i].ItemIdentityCode;
cmd.Parameters.Add("#PurchasingPrice" + i, SqlDbType.Decimal).Value = linesToInsert[i].PurchasingPrice;
cmd.Parameters.Add("#DiscountRate" + i, SqlDbType.Decimal).Value = linesToInsert[i].DiscountRate;
//...
}
conn.Open();
cmd.ExecuteNonQuery();
}
}
This is kind of some nasty code. I don't know if you are new to programming but you should use a Stored Procedure for this where the procedure defines the 14 or so parameters that need to be passed in as arguments. This will guide your code so that you add parameters for the parameterized stored procedure call, each argument will need to be strongly typed and this will guide you to make the right conversions for each column value of your table. You should also create a C# class that defines, as public properties all your table column values. Excuse the VB.NET but you will get the idea with this simple Data Access Layer (D.A.L) example snippet, the UpdateOffer could be renamed AddUpdateOffer and this could check to see whether the record exists or not by passing in the record id to the AddUpdate stored procedure if it is an update, if the record id is null the stored procedure knows to do an insert else update:
Public Class Offer
Public OfferID As Integer
Public PropertyID As Integer
Public AgentUserID As Integer
Public AgentName As String
Public BuyerUserID As Integer
Public BuyerName As String
Public BuyerType As String
Public Offer As Integer
Public NetOffer As Integer
Public ClosingCost As Integer
Public Allowances As Integer
Public RepairCosts As Integer
Public TotalCredits As Integer
Public OfferType As String
Public OfferDate As String
Public ProxyOffer As Integer
Public NetProxyOffer As Integer
Public ResultResponse As SUBMIT_OFFER_RESULT
'Public ResultAcceptedOffer As Integer
Public ResultAcceptedNetOffer As Integer
'Public ResultHighestOffer As Integer
Public ResultHighestNetOffer As Integer
Public Notifications As ArrayList = New ArrayList
Public EarnestMoneyDeposit As Integer
Public DownPayment As Integer
Public TypeOfFinancing As String
Public OfferStatus As String
Public Note As String
Public Visble As Boolean = True
Public OfferStatusChangedDate As DateTime
Public EstimatedCloseDate As DateTime
Public SourceType As String
Public Sub GetOffer(ByVal offerID As Integer)
Dim offerDB As OSP.DataAccess.OfferDB = New OSP.DataAccess.OfferDB
Dim rs As SqlClient.SqlDataReader
rs = offerDB.GetOffer(offerID)
Do While rs.Read
Me.OfferID = offerID
Me.PropertyID = rs("PROPERTY_ID")
Me.AgentUserID = rs("AGENT_USER_ID")
Me.BuyerUserID = IIf(IsDBNull(rs("BUYER_USER_ID")), 0, rs("BUYER_USER_ID"))
Me.Offer = rs("OFFER")
Me.NetOffer = rs("NET_OFFER")
Me.TotalCredits = rs("TOTAL_CREDITS")
Me.ProxyOffer = rs("PROXY_OFFER")
Me.OfferType = rs("OFFERTYPE")
Me.OfferDate = rs("OFFER_DATE")
Me.DownPayment = IIf(IsDBNull(rs("DOWN_PAYMENT")), 0, rs("DOWN_PAYMENT"))
Me.EarnestMoneyDeposit = IIf(IsDBNull(rs("EARNEST_MONEY_DEPOSIT")), 0, rs("EARNEST_MONEY_DEPOSIT"))
Me.TypeOfFinancing = rs("TYPE_OF_FINANCING")
Me.BuyerName = GlobalFunctions.DefaultString(rs("BUYER_NAME"))
Me.BuyerType = GlobalFunctions.DefaultString(rs("BUYER_TYPE"))
Me.AgentName = rs("OFFER_BY_NAME")
Me.OfferStatus = GlobalFunctions.DefaultString(rs("OFFER_STATUS"))
Me.Note = GlobalFunctions.DefaultString(rs("NOTE"))
Me.OfferStatusChangedDate = IIf(IsDBNull(rs("OFFER_STATUS_CHANGED_DATE")), Me.OfferStatusChangedDate, rs("OFFER_STATUS_CHANGED_DATE"))
Me.Visble = IIf(IsDBNull(rs("VISIBLE")), True, rs("VISIBLE"))
Me.EstimatedCloseDate = IIf(IsDBNull(rs("ESTIMATED_CLOSE_DATE")), DateTime.MinValue, rs("ESTIMATED_CLOSE_DATE"))
Loop
Try
If Not rs.IsClosed Then
rs.Close() : rs = Nothing
End If
If Not offerDB Is Nothing Then
offerDB.Dispose() : offerDB = Nothing
End If
Catch : End Try
End Sub
Public Function UpdateOffer() As Integer
Dim offerDB As OSP.DataAccess.OfferDB = New OSP.DataAccess.OfferDB
Return offerDB.UpdateOffer(Me)
End Function
End Class
Public Class OfferDB
Implements System.IDisposable
Dim db As SQLDatabase
Public Sub New()
db = New SQLDatabase(GlobalSettings.GetDefaultConnectionString)
End Sub
Public Sub Dispose() Implements System.IDisposable.Dispose
If Not db Is Nothing Then
db = Nothing
End If
End Sub
Public Function GetOffer(ByVal offerID As Integer) As SqlClient.SqlDataReader
Dim dbCommand As DbCommand = db.GetStoredProcCommand("OSP_GET_OFFER")
db.AddInParameter(dbCommand, "#OFFER_ID", SqlDbType.Int, offerID)
Try
Return db.ExecuteReader(dbCommand)
Catch ex As Exception
Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "EXCEPTION_CRITICAL")
If (rethrow) Then
Throw
End If
End Try
End Function
Public Function UpdateOffer(ByVal offer As OSP.Offer) As Integer
Dim dbCommand As DbCommand = db.GetStoredProcCommand("OSP_UPDATE_OFFER")
db.AddInParameter(dbCommand, "#OFFER_ID", SqlDbType.Int, offer.OfferID)
db.AddInParameter(dbCommand, "#BUYER_USER_ID", SqlDbType.Int, offer.BuyerUserID)
db.AddInParameter(dbCommand, "#OFFER", SqlDbType.Int, offer.Offer)
db.AddInParameter(dbCommand, "#TOTAL_CREDITS", SqlDbType.Int, offer.TotalCredits)
db.AddInParameter(dbCommand, "#OFFER_TYPE", SqlDbType.VarChar, offer.OfferType)
db.AddInParameter(dbCommand, "#OFFER_DATE", SqlDbType.VarChar, offer.OfferDate)
db.AddInParameter(dbCommand, "#TYPE_OF_FINANCING", SqlDbType.VarChar, offer.TypeOfFinancing)
db.AddInParameter(dbCommand, "#DOWN_PAYMENT", SqlDbType.Int, offer.DownPayment)
db.AddInParameter(dbCommand, "#EARNEST_MONEY_DEPOSIT", SqlDbType.Int, offer.EarnestMoneyDeposit)
db.AddInParameter(dbCommand, "#OFFER_STATUS", SqlDbType.VarChar, offer.OfferStatus)
db.AddInParameter(dbCommand, "#NOTE", SqlDbType.VarChar, offer.Note)
If Not offer.OfferStatusChangedDate = DateTime.MinValue Then
db.AddInParameter(dbCommand, "#OFFER_STATUS_CHANGED_DATE", SqlDbType.DateTime, offer.OfferStatusChangedDate)
End If
Try
Return db.ExecuteScalar(dbCommand)
Catch ex As Exception
Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "EXCEPTION_CRITICAL")
If (rethrow) Then
Throw
End If
End Try
End Function
End Class
I've data in DataTable with 2 rows and 3 columns. I want to insert that data into Oracle table.
How can I insert? please give me with some example.
And also
How can I pass datatable to storedprocedure in ORACLE...
I pass datatable in below mensioned manner, but datatable type problem is comming. how can I solve this?
cmd.Parameters.Add("#Details",dtSupplier);
(OR)
cmd.Parameters.Add("Details", DbType.Single).Value = dtSupplier.ToString();
want to insert dataset or a datatable into ORACLE,
create an ORACLE data adapter.
create a command object for insertion,
set the CommandType to StoredProcedure.
Update command of the data adapter,
pass the dataset or datatable as parameter.
like this:
OracleDataAdapter da = new OracleDataAdapter();
OracleCommand cmdOra = new OracleCommand(StoredProcedureName, Connection);
cmdOra.CommandType = CommandType.StoredProcedure;
da.InsertCommand = cmdOra;
da.Update(dsDataSet);
OR
if above dont work than pass datatable as xml prameter than than process it
For details check : ADO.NET DataTable as XML parameter to an Oracle/SQL Server Database Stored Procedure
OR
Check this thread on Oracle site : Thread: Pass data table to Oracle stored procedure
Check existing answer : How to Pass datatable as input to procedure in C#?
I'm very late for this answer, but I elaborated a bit to have some more readable (I hope) code, and to avoid all those .ToString() for the values so nulls and other less common values can be handled; here it is:
public void Copy(String tableName, DataTable dataTable)
{
var insert = $"insert into {tableName} ({GetColumnNames(dataTable)}) values ({GetParamPlaceholders(dataTable)})";
using (var connection = /*a method to get a new open connection*/)
{
for (var row = 0; row < dataTable.Rows.Count; row++)
{
InsertRow(dataTable, insert, connection, row);
}
}
}
private static void InsertRow(DataTable dataTable, String insert, OracleConnection connection, Int32 row)
{
using (var command = new OracleCommand(insert, connection))
{
AssembleParameters(dataTable, command, row);
command.ExecuteNonQuery();
}
}
private static void AssembleParameters(DataTable dataTable, OracleCommand command, Int32 row)
{
for (var col = 0; col < dataTable.Columns.Count; col++)
{
command.Parameters.Add(ParameterFor(dataTable, row, col));
}
}
private static OracleParameter ParameterFor(DataTable dataTable, Int32 row, Int32 col)
{
return new OracleParameter(GetParamName(dataTable.Columns[col]), dataTable.Rows[row].ItemArray.GetValue(col));
}
private static String GetColumnNames(DataTable data) => (from DataColumn column in data.Columns select column.ColumnName).StringJoin(", ");
private static String GetParamPlaceholders(DataTable data) => (from DataColumn column in data.Columns select GetParamName(column)).StringJoin(", ");
private static String GetParamName(DataColumn column) => $":{column.ColumnName}_param";
Hope this can be still useful to somebody
The best idea would be follow the step mentioned below
Create a transaction
Begin the transaction
Loop through you data table
call your procedure
If no error occurred commit transaction
else roll back transaction
Regarding this part of your question:
cmd.Parameters.Add("#Details",dtSupplier);
(OR)
cmd.Parameters.Add("Details", DbType.Single).Value = dtSupplier.ToString();
What is the type of the "Details" parameter? Is it a Single? Then you would have to pick one (1) value from your DataTable and pass it to your parameter, something like dtSupplier.Rows[0]["col"].
If you use dtSupplier.ToString() you are just making a string of the entire DataTable (which i guess will always be the type name of DataTable).
First of all, you need to add Oracle.DataAccess.dll as reference in Visual Studio. In most cases, you can find this dll in the directory C:\ProgramData\Oracle11g\product\11.2.0\client_1\ODP.NET\bin\2.x\Oracle.DataAccess.dll
If just you need to insert the records from DataTable to Oracle table, then you can call the below function. Consider that your DataTable name is dt.
string error = "";
int noOfInserts = DataTableToTable(dt,out error);
1. Without using Oracle Parameters(special character non-safe)
The definition of the function is given below. Here, we are just making the query dynamic for passing this as a sql statement to the InsertWithQuery function.
public int DataTableToTable(DataTable dt,out string error)
{
error = "";
for (int i = 0; i < dt.Rows.Count; i++)
{
finalSql = "INSERT INTO TABLENAME SELECT ";
for (int j = 0; j < dt.Columns.Count; j++)
{
colValue += "'" + dt.Rows[i][j].ToString() + "',";
}
colValue = colValue.Remove(colValue.Length - 1, 1);
finalSql += colValue + " FROM DUAL";
InsertWithQuery(finalSql, out error);
if (error != "")
return error;
inserts++;
colValue = "";
}
}
The code for InsertWithQuery function is given below. Here, in the connection string you have to place you database details like Host,Username,Password etc.
public int InsertWithQuery(string query, out string error)
{
error = "";
int rowsInserted = 0;
if (error == "")
{
OracleConnection con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=)(PORT=)))(CONNECT_DATA=(SERVER=DEDICATED)(SID=)));User Id=;Password=");
OracleTransaction trans = con.BeginTransaction();
try
{
error = "";
OracleCommand cmd = new OracleCommand();
cmd.Transaction = trans;
cmd.Connection = con;
cmd.CommandText = query;
rowsInserted = cmd.ExecuteNonQuery();
trans.Commit();
con.Dispose();
return rowsInserted;
}
catch (Exception ex)
{
trans.Rollback();
error = ex.Message;
rowsInserted = 0;
}
finally
{
con.Dispose();
}
}
return rowsInserted;
}
2. With using Oracle Parameters(special character safe)
This can handle special characters like single quotes like scenarios in the column values.
public int DataTableToTable(DataTable dt,out string error)
{
error = "";
string finalSql = "";
List<string> colValue = new List<string>();
List<string> cols = new List<string>() {"COLUMN1","COLUMN2","COLUMN3"};
for (int i = 0; i < dt.Rows.Count; i++)
{
finalSql = "INSERT INTO TABLENAME(COLUMN1,COLUMN2,COLUMN3) VALUES(:COLUMN1,:COLUMN2,:COLUMN3) ";
for (int j = 0; j < dt.Columns.Count; j++)
{
colValue.Add(dt.Rows[i][j].ToString());
}
objDAL.InsertWithParams(finalSql,colValue,cols, out error);
if (error != "")
return error;
inserts++;
colValue.Clear();
}
}
And the InsertWithParams is given below
public string InsertWithParams(string sql, List<string> colValue, List<string> cols, out string error)
{
error = "";
try
{
OracleConnection con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=)(PORT=)))(CONNECT_DATA=(SERVER=DEDICATED)(SID=)));User Id=;Password=");
OracleCommand command = new OracleCommand(sql, con);
for (int i = 0; i < colValue.Count; i++)
{
command.Parameters.Add(new OracleParameter(cols[i], colValue[i]));
}
command.ExecuteNonQuery();
command.Connection.Close();
}
catch (Exception ex)
{
error = ex.Message;
}
return null;
}
try {
//Suppose you have DataTable dt
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source='Give path of your access database file here';Persist Security Info=False";
OleDbConnection dbConn = new OleDbConnection(connectionString);
dbConn.Open();
using (dbConn)
{
int j = 0;
for (int i = 0; i < 2; i++)
{
OleDbCommand cmd = new OleDbCommand(
"INSERT INTO Participant_Profile ([column1], [column2] , [column3] ) VALUES (#c1 , #c2 , #c3 )", dbConn);
cmd.Parameters.AddWithValue("#c1", dt.rows[i][j].ToString());
cmd.Parameters.AddWithValue("#c2", dt.rows[i][j].ToString());
cmd.Parameters.AddWithValue("#c3", dt.rows[i][j].ToString());
cmd.ExecuteNonQuery();
j++;
}
}
}
catch (OleDbException exception)
{
Console.WriteLine("SQL Error occured: " + exception);
}
I know it's been a big WHILE upon the matter, but the same need: "to insert data from a datatable to an Oracle table" has happened to me. I found this thread. I also tried the answers and came to the conclusion that executing a
...
cmd.ExecuteNonQuery();
...
in a loop, is bad. Reeaaally bad. The first thing that is bad is performance, the second is unnecessary complexity, the third is unnecessary Oracle Objects (stored proc). The time it takes to complete, lets say 200 rows, is almost 1 minute and that's me rounding it down. So in the hope that someone else will find this helpful here's my experience.
I got stubborn and searched some more, so I found out this, true it's from 2018. But I'm in 2021 myself...
So the base code is:
using Oracle.ManagedDataAccess.Client; // you don't need other dll, just install this from nuget gallery
using System.Data;
public static void Datatable2Oracle(string tableName, DataTable dataTable)
{
string connString = "connection string";
OracleBulkCopy copy= new(connString, OracleBulkCopyOptions.UseInternalTransaction /*I don't know what this option does*/);
copy.DestinationTableName = tableName;
copy.WriteToServer(dataTable);
copy.Dispose();
}
This should match a raw oracle DDL performance:
create table table_name as select * from other_table_name
I want to show 10 records per page in a datagridview on a window form and user must click next button to show next 10 records. Is it there some property in DataGridview or do i need to create a custom control.
What i need to do to achieve this.
Here's a simple working example, where a
BindingNavigator GUI control uses a
BindingSource object to
identify page breaks, by setting its DataSource to a custom subclass of IListSource.
(Thanks to this answer for
the key idea.) When the user clicks the "next page" button, the BindingNavigator fires bindingSource1_CurrentChanged and your code can fetch the desired records. Instructions:
Create a Windows Forms application
Drag onto the form a BindingNavigator, a DataGridView, and a BindingSource
Replace Form1.cs with the following code:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace PagedDataGridView
{
public partial class Form1 : Form
{
private const int totalRecords = 43;
private const int pageSize = 10;
public Form1()
{
InitializeComponent();
dataGridView1.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "Index" });
bindingNavigator1.BindingSource = bindingSource1;
bindingSource1.CurrentChanged += new System.EventHandler(bindingSource1_CurrentChanged);
bindingSource1.DataSource = new PageOffsetList();
}
private void bindingSource1_CurrentChanged(object sender, EventArgs e)
{
// The desired page has changed, so fetch the page of records using the "Current" offset
int offset = (int)bindingSource1.Current;
var records = new List<Record>();
for (int i = offset; i < offset + pageSize && i < totalRecords; i++)
records.Add(new Record { Index = i });
dataGridView1.DataSource = records;
}
class Record
{
public int Index { get; set; }
}
class PageOffsetList : System.ComponentModel.IListSource
{
public bool ContainsListCollection { get; protected set; }
public System.Collections.IList GetList()
{
// Return a list of page offsets based on "totalRecords" and "pageSize"
var pageOffsets = new List<int>();
for (int offset = 0; offset < totalRecords; offset += pageSize)
pageOffsets.Add(offset);
return pageOffsets;
}
}
}
}
Here is my solution : It took me almost a year to find it and proud of this one
public class SuperGrid : DataGridView
{
public int PageSize
{
get
{
return _pageSize;
}
set
{
_pageSize = value;
}
}
public int _pageSize = 10;
BindingSource bs = new BindingSource();
BindingList<DataTable> tables = new BindingList<DataTable>();
public void SetPagedDataSource(DataTable dataTable, BindingNavigator bnav)
{
DataTable dt = null;
int counter = 1;
foreach (DataRow dr in dataTable.Rows)
{
if (counter == 1)
{
dt = dataTable.Clone();
tables.Add(dt);
}
dt.Rows.Add(dr.ItemArray);
if (PageSize < ++counter )
{
counter = 1;
}
}
bnav.BindingSource = bs;
bs.DataSource = tables;
bs.PositionChanged += bs_PositionChanged;
bs_PositionChanged(bs, EventArgs.Empty);
}
void bs_PositionChanged(object sender, EventArgs e)
{
this.DataSource = tables[bs.Position];
}
}
How to use it? Add above code to your project, drag the Supergrid and a bindingnavigator control to your win form .
superGrid1.PageSize = 5;
DataTable dt = DataProvider.ExecuteDt("select * from test order by col");
superGrid1.SetPagedDataSource(dt, bindingNavigator1);
And you get a paged Datagridview with data binding without much hastle/
Implement Paging DataGridView in Windows Forms (WinForms) Application using C# and VB.Net, this is another solution :
https://www.aspsnippets.com/Articles/Implement-Paging-DataGridView-in-Windows-Forms-WinForms-Application-using-C-and-VBNet.aspx
In this article It will be explained how to implement Paging DataGridView in Windows Forms (WinForms) Application using C# and VB.Net.
DataGridView control in Windows Forms (WinForms) Application does not have paging capabilities and hence Custom Paging using Stored Procedure needs to be implemented.
The Stored Procedure accepts PageIndex and PageSize as input parameters in order to fetch the records for the desired page index. In order to populate the Pager in front end, the total number of records in the table is needed which is fetched using the RecordCount Output parameter.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
CREATE PROCEDURE [dbo].[GetCustomersPageWise]
#PageIndex INT = 1
,#PageSize INT = 10
,#RecordCount INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SELECT ROW_NUMBER() OVER
(
ORDER BY [CustomerID] ASC
)AS RowNumber
,[CustomerID]
,[ContactName]
,[Country]
INTO #Results
FROM [Customers]
SELECT #RecordCount = COUNT(*)
FROM #Results
SELECT [CustomerID]
,[ContactName]
,[Country]
FROM #Results
WHERE RowNumber BETWEEN(#PageIndex -1) * #PageSize + 1 AND(((#PageIndex -1) * #PageSize + 1) + #PageSize) - 1
DROP TABLE #Results
END
Initially the value of the PageSize is set to 5 and the PageIndex is set as 1. The value of the RecordCount Output parameter and PageIndex are passed to the PopulatePager method (discussed later).
C#
//Set the Page Size.
int PageSize = 5;
private void Form1_Load(object sender, EventArgs e)
{
this.BindGrid(1);
}
private void BindGrid(int pageIndex)
{
string constring = #"Data Source=.\SQL2005;Initial Catalog=Northwind;Integrated Security=true";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("GetCustomersPageWise", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#PageIndex", pageIndex);
cmd.Parameters.AddWithValue("#PageSize", PageSize);
cmd.Parameters.Add("#RecordCount", SqlDbType.Int, 4);
cmd.Parameters["#RecordCount"].Direction = ParameterDirection.Output;
con.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
dataGridView1.DataSource = dt;
con.Close();
int recordCount = Convert.ToInt32(cmd.Parameters["#RecordCount"].Value);
this.PopulatePager(recordCount, pageIndex);
}
}
}
Each dynamic Button is assigned a click event handler, when the Button is clicked the value of its Name is passed as PageIndex parameter to the BindGrid function, which populates the DataGridView with the new set of records.
C#
private void PopulatePager(int recordCount, int currentPage)
{
List<Page> pages = new List<Page>();
int startIndex, endIndex;
int pagerSpan = 5;
//Calculate the Start and End Index of pages to be displayed.
double dblPageCount = (double)((decimal)recordCount / Convert.ToDecimal(PageSize));
int pageCount = (int)Math.Ceiling(dblPageCount);
startIndex = currentPage > 1 && currentPage + pagerSpan - 1 < pagerSpan ? currentPage : 1;
endIndex = pageCount > pagerSpan ? pagerSpan : pageCount;
if (currentPage > pagerSpan % 2)
{
if (currentPage == 2)
{
endIndex = 5;
}
else
{
endIndex = currentPage + 2;
}
}
else
{
endIndex = (pagerSpan - currentPage) + 1;
}
if (endIndex - (pagerSpan - 1) > startIndex)
{
startIndex = endIndex - (pagerSpan - 1);
}
if (endIndex > pageCount)
{
endIndex = pageCount;
startIndex = ((endIndex - pagerSpan) + 1) > 0 ? (endIndex - pagerSpan) + 1 : 1;
}
//Add the First Page Button.
if (currentPage > 1)
{
pages.Add(new Page { Text = "First", Value = "1" });
}
//Add the Previous Button.
if (currentPage > 1)
{
pages.Add(new Page { Text = "<<", Value = (currentPage - 1).ToString() });
}
for (int i = startIndex; i <= endIndex; i++)
{
pages.Add(new Page { Text = i.ToString(), Value = i.ToString(), Selected = i == currentPage });
}
//Add the Next Button.
if (currentPage < pageCount)
{
pages.Add(new Page { Text = ">>", Value = (currentPage + 1).ToString() });
}
//Add the Last Button.
if (currentPage != pageCount)
{
pages.Add(new Page { Text = "Last", Value = pageCount.ToString() });
}
//Clear existing Pager Buttons.
pnlPager.Controls.Clear();
//Loop and add Buttons for Pager.
int count = 0;
foreach (Page page in pages)
{
Button btnPage = new Button();
btnPage.Location = new System.Drawing.Point(38 * count, 5);
btnPage.Size = new System.Drawing.Size(35, 20);
btnPage.Name = page.Value;
btnPage.Text = page.Text;
btnPage.Enabled = !page.Selected;
btnPage.Click += new System.EventHandler(this.Page_Click);
pnlPager.Controls.Add(btnPage);
count++;
}
}
private void Page_Click(object sender, EventArgs e)
{
Button btnPager = (sender as Button);
this.BindGrid(int.Parse(btnPager.Name));
}
public class Page
{
public string Text { get; set; }
public string Value { get; set; }
public bool Selected { get; set; }
}
Another Approach for this problem:
public class PagedGrid : DataGridView
{
Paging pg;
SQLQuery s;
public void SetPagedDataSource( SQLQuery s, BindingNavigator bnav)
{
this.s = s;
int count = DataProvider.ExecuteCount(s.CountQuery);
pg = new Paging(count, 5);
bnav.BindingSource = pg.BindingSource;
pg.BindingSource.PositionChanged += new EventHandler(bs_PositionChanged);
//first page
string q = s.GetPagingQuery(pg.GetStartRowNum(1), pg.GetEndRowNum(1), true);
DataTable dt = DataProvider.ExecuteDt(q);
DataSource = dt;
}
void bs_PositionChanged(object sender, EventArgs e)
{
int pos = ((BindingSource)sender).Position + 1;
string q = s.GetPagingQuery(pg.GetStartRowNum(pos), pg.GetEndRowNum(pos), false);
DataTable dt = DataProvider.ExecuteDt(q);
DataSource = dt;
}
public void UpdateData()
{
DataTable dt = (DataTable)DataSource;
using (SqlConnection con = new SqlConnection(DataProvider.conStr))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(s.CompleteQuery, con);
SqlCommandBuilder cb = new SqlCommandBuilder(da);
da.UpdateCommand = cb.GetUpdateCommand();
da.InsertCommand = cb.GetInsertCommand();
da.DeleteCommand = cb.GetDeleteCommand();
da.Update(dt);
}
MessageBox.Show("The changes are committed to database!");
}
}
/// <summary>
/// Gives functionality of next page , etc for paging.
/// </summary>
public class Paging
{
public int _totalSize = 0;
private int _pageSize = 0;
public int TotalSize
{
get
{
return _totalSize;
}
set
{
if (value <= 0)
{
throw new ArgumentException();
}
_totalSize = value;
}
}
public int PageSize
{
get
{
return _pageSize;
}
set
{
if (value <= 0)
{
throw new ArgumentException();
}
_pageSize = value;
}
}
public Paging(int totalSize, int pageSize)
{
this.TotalSize = totalSize;
this.PageSize = pageSize;
}
public int GetStartRowNum(int PageNum)
{
if (PageNum < 1)
{
throw new Exception("Page number starts at 1");
}
if (PageNum > GetPageCount())
{
throw new Exception("Page number starts at " + GetPageCount().ToString());
}
return 1 + ((PageNum - 1) * _pageSize);
}
public int GetEndRowNum(int PageNum)
{
if (PageNum < 1)
{
throw new Exception("Page number starts at 1");
}
if (PageNum > GetPageCount())
{
throw new Exception("Page number starts at " + GetPageCount().ToString());
}
return _pageSize + ((PageNum - 1) * _pageSize);
}
public int GetPageCount()
{
return (int)Math.Ceiling(TotalSize / (decimal)PageSize);
}
public bool IsFirstPage(int PageNum)
{
if (PageNum == 1)
{
return true;
}
return false;
}
public bool IsLastPage(int PageNum)
{
if (PageNum == GetPageCount())
{
return true;
}
return false;
}
private int _currentPage = 1;
public int CurrentPage
{
get
{
return _currentPage;
}
set
{
_currentPage = value;
}
}
public int NextPage
{
get
{
if (CurrentPage + 1 <= GetPageCount())
{
_currentPage = _currentPage + 1;
}
return _currentPage;
}
}
public int PreviousPage
{
get
{
if (_currentPage - 1 >= 1)
{
_currentPage = _currentPage - 1;
}
return _currentPage;
}
}
private BindingSource _bindingSource = null;
public BindingSource BindingSource
{
get
{
if (_bindingSource == null)
{
_bindingSource = new BindingSource();
List<int> test = new List<int>();
for (int i = 0; i < GetPageCount(); i++)
{
test.Add(i);
}
_bindingSource.DataSource = test;
}
return _bindingSource;
}
}
}
/// <summary>
/// Query Helper of Paging
/// </summary>
public class SQLQuery
{
private string IDColumn = "";
private string WherePart = " 1=1 ";
private string FromPart = "";
private string SelectPart = "";
public SQLQuery(string SelectPart, string FromPart, string WherePart, string IDColumn)
{
this.IDColumn = IDColumn;
this.WherePart = WherePart;
this.FromPart = FromPart;
this.SelectPart = SelectPart;
}
public string CompleteQuery
{
get
{
if (WherePart.Trim().Length > 0)
{
return string.Format("Select {0} from {1} where {2} ", SelectPart, FromPart, WherePart);
}
else
{
return string.Format("Select {0} from {1} ", SelectPart, FromPart);
}
}
}
public string CountQuery
{
get
{
if (WherePart.Trim().Length > 0)
{
return string.Format("Select count(*) from {0} where {1} ", FromPart, WherePart);
}
else
{
return string.Format("Select count(*) from {0} ", FromPart);
}
}
}
public string GetPagingQuery(int fromrow, int torow, bool isSerial)
{
fromrow--;
if (isSerial)
{
return string.Format("{0} where {1} >= {2} and {1} <= {3}", CompleteQuery, IDColumn, fromrow, torow);
}
else
{
string select1 = "";
string select2 = "";
if (WherePart.Trim().Length > 0)
{
select1 = string.Format("Select top {3} {0} from {1} where {2} ", SelectPart, FromPart, WherePart, torow.ToString());
select2 = string.Format("Select top {3} {0} from {1} where {2} ", SelectPart, FromPart, WherePart, fromrow.ToString());
}
else
{
select1 = string.Format("Select top {2} {0} from {1} ", SelectPart, FromPart, torow.ToString());
select2 = string.Format("Select top {2} {0} from {1} ", SelectPart, FromPart, fromrow.ToString());
}
if (fromrow <= 1)
{
return select1;
}
else
{
return string.Format("{0} except {1} ", select1, select2);
}
}
}
}
using it:
private void Form1_Load(object sender, EventArgs e)
{
SQLQuery s = new SQLQuery("*", "table", "", "id");
pagedGrid1.SetPagedDataSource(s, bindingNavigator1);
}
Note: The DataPrivier class is not included here , it is a simple class that returns datatable from any source.
Try this,
this code is for OleDb, but also works for SqlServer connections.
The dt (DataTable) object is filled with selected page rows, assuming that page starts with 1 (not 0)
public DataTable getData(string sql, int pgNo, int totalRows)
{
DataTable dt = null;
using (OleDbConnection conn = new OleDbConnection(connStr))
{
try
{
DataSet ds;
conn.Open();
ds = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter(sql, conn);
adapter.Fill(ds, (pgNo-1)*totalRows, totalRows, "Table");
conn.Close();
dt = ds.Tables[0];
}
catch (Exception ex)
{if (conn != null) conn.Dispose();}
return dt;
}
My answer is 10years late and I can't begin to explain why. But I think what is important is that I have something to offer. :D
I love to solve problems in the simplest way possible and by far this is the simplest way I use. If there are any issues with it, am glad to fix it.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Drawing;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SqlDataAdapter pagingAdapter;
DataSet pagingDS;
int scrollVal; // This defines how many more data sets there are to load
int rowsPerPage = 10; // This defines the total number of rows to show
public Form1()
{
InitializeComponent();
scrollVal = 0;
}
private void BtnShowresults_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
string sql = "SELECT * FROM Authors";
SqlConnection connection = new SqlConnection(connectionString);
pagingAdapter = new SqlDataAdapter(sql, connection);
pagingDS = new DataSet();
connection.Open();
//This part will get the total number of records from the query
pagingAdapter.Fill(dataSetProjects);
DataTable dataTable = pagingDS.Tables[0];
int rowCount = Convert.ToInt32(dataTable.Rows.Count);
this.btnShowresults.Tag = rowCount; // We set it to the button tag
pagingAdapter.Fill(pagingDS, scrollVal, rowsPerPage, "Authors_table");
connection.Close();
dataGridView1.DataSource = pagingDS;
dataGridView1.DataMember = "Authors_table";
}
private void btnPrevious_Click(object sender, EventArgs e)
{
if (scrollVal < = 0)
{
scrollVal = 0;
} else
{
scrollVal -= rowsPerPage;
}
pagingDS.Clear();
pagingAdapter.Fill(pagingDS, scrollVal, rowsPerPage, "authors_table");
}
private void BtnNext_Click(object sender, EventArgs e)
{
Button btnShowresults = (Button)pnSearch.Controls["btnShowresults"];
int resCount = Convert.ToInt32(btnShowresults.Tag);
if (scrollVal <= resCount)
{
scrollVal = rowsPerPage;
} else
{
scrollVal = rowsPerPage;
}
pagingDS.Clear();
pagingAdapter.Fill(pagingDS, scrollVal, rowsPerPage, "authors_table");
}
}
}
This code is found on http://csharp.net-informations.com/datagridview/csharp-datagridview-paging.htm. It had a few bugs I needed to fix. Consider this a cleaned up version.
Paging emulation with RadGridView for WinForms is possible, especially if we take full advantage of LINQ. This approach also gives us another advantage - client performance. The data processing (filtering, sorting and paging) is obviously done by the SQL server, which is fully optimized for such things, rather than the application. The client only processes and shows one page at a time, rather than all million records. Here I do not use RadGridView’s Virtual Mode - this is a topic for a more advanced blog post.
this link my help you :paging-with-radgridview
https://www.telerik.com/blogs/emulating-paging-with-radgridview-for-winforms-and-linq-with-1-million-records
and the code is:
private void BindGrid()
{
this.radGridView1.GridElement.BeginUpdate();
IQueryable queryable = new DataClasses1DataContext().MyTables.AsQueryable();
if (!String.IsNullOrEmpty(where))
{
queryable = queryable.Where(where);
}
if (!String.IsNullOrEmpty(orderBy))
{
queryable = queryable.OrderBy(orderBy);
}
radGridView1.DataSource = queryable.Skip(currentPageIndex * pageSize).Take(pageSize);
this.radGridView1.GridElement.EndUpdate(true);
EnableDisablePager();
}
I did manual paging on my datagridview. I hope this helps
private void btnBack_Click(object sender, EventArgs e)
{
int a = int.Parse(lblmin.Text);
int b = int.Parse(lblmax.Text);
int c = a - 100;
int d = b - 100;
if (lblmin.Text != "1")
{
String name = "Main";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
"C:\\BBISDatabase\\Data.xlsx" +
";Extended Properties='Excel 8.0;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$] where IDs between " + c.ToString() + " and " + d.ToString() + "", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
dgMain.DataSource = data;
lblcount.Text = c.ToString();
lblmax.Text = d.ToString();
}
else
{
btnBack.Visible = false;
}
}
private void btnNext_Click(object sender, EventArgs e)
{
int a = int.Parse(lblmin.Text);
int b = int.Parse(lblmax.Text);
int c = b + 1;
int d = b + 100;
String name = "Main";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
"C:\\BBISDatabase\\Data.xlsx" +
";Extended Properties='Excel 8.0;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$] where IDs between "+c.ToString()+" and "+d.ToString()+"", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
dgMain.DataSource = data;
lblmin.Text = c.ToString();
lblmax.Text = d.ToString();
btnBack.Visible = true;
}
and i put this code on form_load():
lblmin.Text = "1";