Inserting a foreign key value & binding gridview at the same time - c#

I need some help on how to achieved Inserting a foreign key value in MS SQL at the same time binding the result in gridview in the same aspx page.
I have my code which is works fine and no error upon Build Solution but it shows the following line error in the browser.
Line: 940 Error: Sys.WebForms.PageRequestManagerServerErrorException:
A field or property with the name 'TypeName' was not found on the
selected data source.
I'm using MS SQL 2008 & MS Visual Studio 2013
Below is my code in my project
ASPX Gridview:
<!-- Main Gridview -->
<asp:GridView ID="gvItemgrid" runat="server" AutoGenerateColumns="false" DataKeyNames="ItemID"
ShowHeader="false" CssClass="Grid">
<RowStyle Wrap="false" CssClass="row" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="imgbtn" ImageUrl="../images/Edit.jpg" runat="server" Width="12px" Height="12px" OnClick="imgbtn_Click" /></ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="50px" DataField="ItemID" HeaderText="ItemID" />
<asp:BoundField ItemStyle-Width="500px" DataField="ItemName" HeaderText="ItemName" />
<asp:BoundField ItemStyle-Width="500px" DataField="TypeName" HeaderText="TypeName" />
</Columns>
</asp:GridView>
C# Code:
// C# Code
#region BindTypeList (ddlType)
// bind the Type list in drop down list..
private void BindTypeList(DropDownList ddlType)
{
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("select * from inv_TypeList");
cmd.Connection = con;
con.Open();
this.ddlType.DataSource = cmd.ExecuteReader();
this.ddlType.DataTextField = "TypeName";
this.ddlType.DataValueField = "TypeID";
this.ddlType.DataBind();
con.Close();
}
#endregion
//button save
#region btnSave
protected void btnSave_Click(object sender, EventArgs e)
{
//Calling the database for Insert Statement
SqlConnection con = new SqlConnection(strConnString);
// call stored procedure
SqlCommand cmd = new SqlCommand("inv_ItemList_Insert", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
// add values
cmd.Parameters.AddWithValue("#ItemName", txtItemName.Text);
cmd.Parameters["#ItemName"].Value = txtItemName.Text;
cmd.Parameters.AddWithValue("#TypeID", ddlType.SelectedItem.Value);
cmd.Parameters["#TypeID"].Value = ddlType.SelectedItem.Value;
// add the result
cmd.Parameters.Add(new SqlParameter("#Result", SqlDbType.VarChar, 1000));
cmd.Parameters["#Result"].Direction = ParameterDirection.Output;
try
{
// open the database..
con.Open();
cmd.ExecuteNonQuery();
// perform some actions here..
//btnSave.Enabled = false;
string result = cmd.Parameters["#Result"].Value.ToString();
// label notification..
lblMsg.Visible = false;
lblMsg.Text = result;
BindGrid();
// if meets condition to perform some actions..
if ((lblMsg.Text == ("Item Name: " + (txtItemName.Text + (" " + "already exists..")))))
{
// controls set to active..
txtItemName.Enabled = true;
ddlType.Enabled = true;
//txtRegister.Text = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt");
txtItemName.Focus();
// lblMsg notification display
lblMsg.Attributes.Add("style", "color: #FFFFFF");
lblMsg.Attributes.Add("style", "background-color: OrangeRed");
lblMsg.Visible = false;
btnNew.Enabled = false;
// javascript messagebox "IP Address exist!"
ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "msgExist", "msgExist();", true);
}
else
{
//Method in displaying data in reverse (last - first)
//Calling the database
SqlConnection con2 = new SqlConnection(strConnString);
string strConString = "select * from inv_ItemList order by ItemID DESC";
SqlCommand cmd2 = new SqlCommand(strConString);
gvItemgrid.DataSource = GetData(strConString);
gvItemgrid.DataBind();
//Highlighting the first row in gridview
object firstRowIndex = gvItemgrid.Rows[0];
gvItemgrid.Rows[0].BackColor = System.Drawing.Color.LemonChiffon;
//Display records
//current record per page
int val1 = Convert.ToInt32(gvItemgrid.Rows.Count.ToString());
int val2 = Convert.ToInt32(lblcurrentpage.Text.ToString());
int val3 = val1 * val2;
lblrecperpage.Text = Convert.ToString(val3);
//display page
lbltotalpage.Text = lblcurrentpage.Text;
//paging function disabled..
btnFirst.Enabled = false;
btnNext.Enabled = false;
btnPrevious.Enabled = false;
btnLast.Enabled = false;
//controls set to disabled
txtItemName.Enabled = false;
btnSave.Enabled = false;
////current date and time
//txtRegister.Text = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt");
// lblMsg notification display
lblMsg.Attributes.Add("style", "color:#FFFFFF");
lblMsg.Attributes.Add("style", "background-color:Green");
// javascript messagebox "Data successfully saved"
ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "msgSave", "msgSave();", true);
}
}
//catching internal error
catch (SqlException ex)
{
// throw some internal error in case there is
string errorMessage = "Error in registring user";
errorMessage = (errorMessage + ex.Message);
throw new Exception(errorMessage);
}
finally
{
//close the database..
con.Close();
}
// button new enabled..
btnNew.Enabled = true;
}
#endregion
// bind grid..
#region BindGrid
private void BindGrid()
{
// Call the Database & Stored Procedure for total Records
SqlConnection myConnection = new SqlConnection(strConnString);
SqlCommand myCommand = new SqlCommand("inv_ItemList_BindGrid", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue("#startRowIndex", currentPageNumber);
myCommand.Parameters.AddWithValue("#maximumRows", PAGE_SIZE);
myCommand.Parameters.Add("#totalRows", SqlDbType.Int, 4);
myCommand.Parameters["#totalRows"].Direction = ParameterDirection.Output;
myCommand.Parameters.Add("#totalRec", SqlDbType.Int, 4);
myCommand.Parameters["#totalRec"].Direction = ParameterDirection.Output;
SqlDataAdapter ad = new SqlDataAdapter(myCommand);
DataSet ds = new DataSet();
ad.Fill(ds);
gvItemgrid.DataSource = ds;
gvItemgrid.DataBind();
// Display the total records & pages..
double totalRows = int.Parse(myCommand.Parameters["#totalRows"].Value.ToString());
double totalRec = int.Parse(myCommand.Parameters["#totalRec"].Value.ToString());
lbltotalrec.Text = CalculateTotalRow(totalRec).ToString();
lbltotalpage.Text = CalculateTotalPages(totalRows).ToString();
// current page value
lblcurrentpage.Text = currentPageNumber.ToString();
// conditional meets
if ((currentPageNumber == 1))
{
// button first & prev disabled..
btnFirst.Enabled = false;
btnPrevious.Enabled = false;
if ((Int32.Parse(lbltotalpage.Text.ToString()) > 0))
{
btnNext.Enabled = true;
btnLast.Enabled = true;
}
else
{
btnNext.Enabled = false;
}
}
else
{
btnPrevious.Enabled = true;
btnFirst.Enabled = true;
if ((currentPageNumber == Int32.Parse(lbltotalpage.Text.ToString())))
{
btnNext.Enabled = false;
btnLast.Enabled = false;
}
else
{
btnNext.Enabled = true;
btnLast.Enabled = true;
}
}
//current record per page
int val1 = Convert.ToInt32(gvItemgrid.Rows.Count.ToString());
int val2 = Convert.ToInt32(lblcurrentpage.Text.ToString());
int val3 = val1 * val2;
lblrecperpage.Text = Convert.ToString(val3);
// conditional meets equalize the last page value & records..
if ((btnLast.Enabled == false))
{
lblrecperpage.Text = "";
lblrecperpage.Text = totalRec.ToString();
}
else
{
// point out the record at the end of the page..
lblrecperpage.Text = Convert.ToString(val3);
}
// condition
if ((lblrecperpage.Text == lbltotalrec.Text))
{
btnNext.Enabled = false;
btnLast.Enabled = false;
}
else
{
btnNext.Enabled = true;
btnLast.Enabled = true;
}
}
#endregion
SQL Stored Procedure: inv_ItemList_Insert
ALTER PROCEDURE [dbo].[inv_ItemList_Insert]
-- Add the parameters for the stored procedure here
#ItemName VARCHAR(50),
#TypeID INT,
#Result VARCHAR (1000) OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
IF EXISTS (SELECT ItemName FROM dbo.inv_ItemList WHERE ItemName = RTRIM(#ItemName))
BEGIN
SET #Result = 'Item Name: '+ LTRIM(RTRIM(#ItemName)) + ' ' + 'already exists..'
END
ELSE
BEGIN
INSERT INTO [inv_ItemList] ([ItemName], [TypeID])
VALUES (#ItemName, #TypeID);
SET #Result = 'Item Name: '+ LTRIM(RTRIM(#ItemName)) + ' ' + 'is successfully added..'
End
END
SQL Stored Procedure: inv_ItemList_BindGrid
ALTER PROCEDURE [dbo].[inv_ItemList_BindGrid]
-- Add the parameters for the stored procedure here
#startRowIndex int,
#maximumRows int,
#totalRows int OUTPUT,
#totalRec int OUTPUT
AS
DECLARE #first_id int, #startRow int
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SET #startRowIndex = ((#startRowIndex - 1) * #maximumRows) + 1
IF #startRowIndex = 0
SET #startRowIndex = 1
SET ROWCOUNT #startRowIndex
-- Insert statements for procedure here
SELECT #first_id = ItemID FROM inv_ItemList ORDER BY ItemID
PRINT #first_id
SET ROWCOUNT #maximumRows
SELECT ItemID, ItemName, inv_TypeList.TypeName FROM inv_ItemList
inner join inv_TypeList on inv_ItemList.TypeID=inv_TypeList.TypeID
WHERE
ItemID >= #first_id
ORDER BY ItemID
SET ROWCOUNT 0
-- GEt the total rows
SELECT #totalRows = COUNT(ItemID) FROM inv_ItemList
SELECT #totalRec = COUNT(*) FROM inv_ItemList
END
Is there anything I missed in my code or any other way to achieved my requirements.
Thank you in advance for your help!

I troubleshoot my code already and I found where the error occurs.
I revised the following SQL statement in my SAVE button
//Method in displaying data in reverse (last - first)
//Calling the database
SqlConnection con2 = new SqlConnection(strConnString);
string strConString = "select * from inv_ItemList order by ItemID DESC";
with this one
string strConString = "SELECT ItemID, ItemName, inv_TypeList.TypeName FROM inv_ItemList inner join inv_TypeList on inv_ItemList.TypeID=inv_TypeList.TypeID order by ItemID DESC";
The error doesn't show up anymore, That's where it solved the error.
Thank you guys for your help!:)

Related

Query is not checking database AdvID itself and delete

i want the query to check database AdvID itself and delete when page is loaded. Why am i getting this error call "System.Data.SqlClient.SqlException: 'Procedure or function 'DeleteByDate' expects parameter '#AdvID', which was not supplied." Shouldnt it check the database itself and delete? why do i have to supply it with AdvID? Here is my page_load code
protected void Page_Load(object sender, EventArgs e)
{
//Generate auto ID
SqlDataAdapter sad = new SqlDataAdapter("Select isnull(max(cast(AdvID as int)),0)+1 from Advertisement", sqlCon);
DataTable dt = new DataTable();
sad.Fill(dt);
advertismentIdTb.Text = dt.Rows[0][0].ToString();
//PageLoadValidations
statusTb.Text = "1";
endDateTb.Attributes["min"] = DateTime.Now.ToString("yyyy-MM-dd");
btnDelete.Enabled = false;
btnUpdate.Enabled = false;
Image1.Visible = false;
//Delete from DB Condition (EndDate)
if (sqlCon.State == ConnectionState.Closed)
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("DeleteByDate", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.ExecuteNonQuery();
sqlCon.Close();
//Show GridView
FillGridView();
}
And here is my script
ALTER PROC [dbo].[DeleteByDate]
#AdvID int
AS
BEGIN
DECLARE #CurrentDate DATE = GETDATE() -- to get current date
-- Assuming that Advertisement table has the column EndDate
IF EXISTS (SELECT * FROM Advertisement a WHERE a.EndDate < #CurrentDate )
BEGIN
UPDATE a SET a.Status = 0
FROM Advertisement a
WHERE a.AdvID = #AdvID
END
END
I think you are asking for a query which will delete all advertisements that ended earlier than right now? Your current query is checking if there are any advertisements that ended before right now then deleted the one with the ID you pass in.
Based on the above assumption, try the following query:
ALTER PROC [dbo].[DeleteByDate]
AS BEGIN
UPDATE a
SET a.Status = 0
FROM Advertisement a
WHERE a.EndDate < GETDATE()
END

c# update if record exists else insert new record

I have code that inserts data into a table when a user enters certain values into three boxes on the page.
The boxes are order number, total weight and tracking reference.
I now need to add further functionality to this code and check first to see if the order number exists, if it does i need to update the columns, if it doesn't I need to insert a new row and add data to that.
I was thinking simply, something like IF results = 0, Insert NEW, ELSE update
How can I modify my code to do this?
protected void Page_Load(object sender, EventArgs e)
{
errorLabel.Visible = false;
successLabel.Visible = false;
errorPanel.Visible = false;
}
protected void submitBtn_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
int _orderID = Convert.ToInt32(orderID.Text);
string _trackingID = trackingNumber.Text;
DateTime _date = DateTime.UtcNow;
int _weightID = Convert.ToInt32(weightID.Text);
SqlConnection myConnection = new SqlConnection("Data Source=localhost\\Sqlexpress;Initial Catalog=databasename;User ID=username;Password=password");
SqlCommand myCommand = new SqlCommand("INSERT into Shipment (TrackingNumber, OrderId, ShippedDateUtc, CreatedOnUtc, TotalWeight) VALUES (#tracking, #order, #date, #date, #weight)", myConnection);
try
{
myConnection.Open();
myCommand.Parameters.AddWithValue("#order", _orderID);
myCommand.Parameters.AddWithValue("#tracking", _trackingID);
myCommand.Parameters.AddWithValue("#date", _date);
myCommand.Parameters.AddWithValue("#weight", _weightID);
int rowsUpdated = myCommand.ExecuteNonQuery();
myConnection.Close();
if (rowsUpdated > 0)
{
alertdiv.Attributes.Add("class", "alert alert-success form-signin");
successLabel.Text = "Thank you, tracking details have been updated";
successLabel.Visible = true;
errorPanel.Visible = true;
}
else
{
alertdiv.Attributes.Add("class", "alert alert-error form-signin");
errorLabel.Text = "Oh dear, the order number is not recognised, please check and try again";
errorLabel.Visible = true;
errorPanel.Visible = true;
}
orderID.Text = "";
trackingNumber.Text = "";
weightID.Text = "";
}
catch (Exception f)
{
errorLabel.Text = "This order number does not exist, please check";
errorLabel.Visible = true;
errorPanel.Visible = true;
return;
}
}
}
protected void Signout_Click(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
Response.Redirect("Login.aspx");
}
You can add some SELECT query before your INSERT statement. So if the SELECT query returns more than one row, it means that you already have that record in the DB, and need to update. So, in general it will be like
SqlCommand cmdCount = new SqlCommand("SELECT count(*) from Shipment WHERE OrderId = #order", myConnection);
cmdCount.Parameters.AddWithValue("#order", _orderID);
int count = (int)cmdCount.ExecuteScalar();
if (count > 0)
{
// UPDATE STATEMENT
SqlCommand updCommand = new SqlCommand("UPDATE Shipment SET TrackingNumber = #tracking, ShippedDateUtc = #date, TotalWeight = #weight", myConnection);
updCommand.Parameters.AddWithValue("#order", _orderID);
updCommand.Parameters.AddWithValue("#tracking", _trackingID);
updCommand.Parameters.AddWithValue("#date", _date);
updCommand.Parameters.AddWithValue("#weight", _weightID);
int rowsUpdated = myCommand.ExecuteNonQuery();
}
else
{
// INSERT STATEMENT
SqlCommand insCommand = new SqlCommand("INSERT into Shipment (TrackingNumber, OrderId, ShippedDateUtc, CreatedOnUtc, TotalWeight) VALUES (#tracking, #order, #date, #date, #weight)", myConnection);
insCommand.Parameters.AddWithValue("#order", _orderID);
insCommand.Parameters.AddWithValue("#tracking", _trackingID);
insCommand.Parameters.AddWithValue("#date", _date);
insCommand.Parameters.AddWithValue("#weight", _weightID);
int rowsUpdated = myCommand.ExecuteNonQuery();
}
Edit:
Or much shorter:
SqlCommand command;
if (count > 0)
{
command = new SqlCommand("UPDATE Shipment SET TrackingNumber = #tracking, ShippedDateUtc = #date, TotalWeight = #weight WHERE OrderId = #order", myConnection);
}
else
{
command = new SqlCommand("INSERT into Shipment (TrackingNumber, OrderId, ShippedDateUtc, CreatedOnUtc, TotalWeight) VALUES (#tracking, #order, #date, #date, #weight)", myConnection);
}
command.Parameters.AddWithValue("#order", _orderID);
command.Parameters.AddWithValue("#tracking", _trackingID);
command.Parameters.AddWithValue("#date", _date);
command.Parameters.AddWithValue("#weight", _weightID);
int rowsUpdated = command.ExecuteNonQuery();
The most efficient way would be to put the functionality into a Stored Procedure, for instance (pseudo-code):
IF EXISTS(SELECT * FROM Orders WHERE OrderNo = #orderNo)
UPDATE ...
ELSE
INSERT ...
If you cannot create a new stored procedure, you can also create a command that contains this Statement though readability is typically worse.
Both approaches require only one DB-request.
If you like receive all data and check if exist any record use HasRows.
using (SqlConnection connection = new SqlConnection("server name"))
{
SqlCommand cmd = new SqlCommand("select * From Shipment where OrderId =#OrderId", connection);
connection.Open();
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.HasRows==true)//check have any recorder
{
while (sdr.Read())
{
Debug.Print("Exist recorder, example.: "+sdr["_trackingID"]);
}
}
else
{
Debug.Print("not exist recorder");
}
connection.Close();
}

SQL insert command only working once in a loop

This is s for loop and it will go to the times and will put the time column as true. This works for the first time, but when the time increases by 0.5, it stays false. The for loop is working as i tried a MessageBox.Show("" + Time1 + ""); inside the for loop.
for (double Time = time_began_5; Time < time_finished_5; Time = Time + 0.5)
{
string Time1 = Time.ToString("0.00");
try
{
SqlConnection cn = new SqlConnection("Data Source=.\\SqlExpress;Initial Catalog=AllensCroft;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework;");
cn.Open();
SqlCommand Command = new SqlCommand("INSERT INTO Slots ([Date],[RoomID],[" + Time1 + "]) Values (#date,#room,1)", cn);
Command.Parameters.AddWithValue("date", date);
Command.Parameters.AddWithValue("room", rooms_combo.SelectedValue);
Command.ExecuteNonQuery();
try
{
cn.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Here is what the database looks like, the first true field works, but when it loops to another time, it remains false, I think it may be due to the fact that if I have an existing row with that date (date is primary key), i cannot update that row, so i might need to have an IF the row exists, update, else create a new row.
Try this, you don't have to open connection in each loop, create your sql statement first looping through each value and then do insert using one statement
private string CreateInsertStatement(double time_began_5, double time_finished_5)
{
string sql = "INSERT INTO Slots ([Date],[RoomID],";
string valuesql = " Values (#date,#room,";
for (double Time = time_began_5; Time < time_finished_5; Time = Time + 0.5)
{
string Time1 = Time.ToString("0.00");
sql+ = "[" + Time1 + "],";
valuesql+ = "1,";
}
sql = sql.TrimEnd(',') + ") ";
valuesql = valuesql.TrimEnd(',') + ") ";
return sql + valuesql;
}
private string CreateUpdateStatement(double time_began_5, double time_finished_5)
{
string sql = "UPDATE Slots SET ";
string wheresql = " WHERE [Date] = #date AND [RoomID] = #room";
for (double Time = time_began_5; Time < time_finished_5; Time = Time + 0.5)
{
string Time1 = Time.ToString("0.00");
sql+ = "[" + Time1 + "] = 1,";
}
sql = sql.TrimEnd(',');
return sql + wheresql;
}
Then in you actual insert code:
try
{
SqlConnection cn = new SqlConnection("Data Source=.\\SqlExpress;Initial Catalog=AllensCroft;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework;");
cn.Open();
SqlCommand Command;
//check if row exists
Command = new SqlCommand("select count(*) from Slots WHERE [Date] = #date AND [RoomID] = #room", cn);
Command.Parameters.AddWithValue("date", date);
Command.Parameters.AddWithValue("room", rooms_combo.SelectedValue);
var cnt = Command.ExecuteScalar();
if(cnt!=null)
{
string sqlstr = ""
if(Int32.Parse(cnt.ToString()) > 0)
{
sqlstr = CreateUpdateStatement(time_began_5,time_finished_5);
}
else if(Int32.Parse(cnt.ToString()) == 0)
{
sqlstr = CreateInsertStatement(time_began_5,time_finished_5);
}
Command = new SqlCommand(sqlstr, cn);
Command.Parameters.AddWithValue("date", date);
Command.Parameters.AddWithValue("room", rooms_combo.SelectedValue);
Command.ExecuteNonQuery();
}
try
{
cn.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
You are doing an insert.
In every loop you insert a new row and set the value true only for the column which name is equal to the current value of the variable Time1.
Not having a value for the other columns they probably default to false. (bit columns I suppose)
If you want a default to true for every column perhaps it is better to change the database schema adding the default for every time column, otherwise you need a long list of parameters
EDIT: If your logic dictates that you need only one row per date and set every time column to true if you enter the situation above then you can move this logic in the database using a stored procedure:
CREATE PROCEDURE InsertOrUpdateSlotFromCode(#dt smalldatetime, #roomID int)
AS
BEGIN
DECLARE #cnt INT
SELECT #cnt = COUNT(*) from Slots WHERE [Date] = #dt
if #cnt = 0
INSERT INTO Slots ([Date],[RoomID], <here all the time fields> VALUES (#dt, #roomID, 1, ....)
else
UPDATE Slots SET [09.00] = 1, ..... WHERE [Date] = #dt
End
END
then your code call the sp
using(SqlConnection cn = new SqlConnection(.........))
{
cn.Open();
SqlCommand Command = new SqlCommand("InsertOrUpdateSlotFromCode", cn);
Command.CommandType = CommandType.StoredProcedure;
Command.Parameters.AddWithValue("date", date);
Command.Parameters.AddWithValue("room", rooms_combo.SelectedValue);
Command.ExecuteNonQuery();
}
Of course now you can completely get rid of the loop

How to paginate a gridview and SQL custom query with ROW_NUMBER

I have a page that executes a custom query that its saved somewhere on the database.
I need to be able to enable pagination on the gridview.
For example purposes the query saved on the database its like this:
select * from requestbases
This returns 10,000 rows.
With the method below I make it return 10 rows.
public DataTable GetGenericResults(string strsql, int pageIndex)
{
StringBuilder sb = new StringBuilder();
sb.Append("WITH MyPagedData as ( ");
int indexFrom = strsql.IndexOf("from");
sb.Append(strsql.Substring(0, indexFrom));
sb.Append(", ");
sb.Append("ROW_NUMBER() OVER(ORDER BY RequestBaseId DESC) as RowNum ");
sb.Append(strsql.Substring(indexFrom));
sb.Append(") ");
sb.Append("SELECT * from MyPagedData where RowNum between #StartIndex and #StartIndex + 10");
using(var connection = (SqlConnection)_context.Database.Connection)
{
var adapter = new SqlDataAdapter(sb.ToString(), connection);
adapter.SelectCommand.Parameters.Add("#StartIndex", SqlDbType.Int).Value = pageIndex;
var results = new DataSet();
adapter.Fill(results, "Results");
return results.Tables["Results"];
}
}
And this is the code to bind the grid
var datatable = RequestBaseBL.GetGenericResults(query.QuerySql, 0);
if (datatable.Rows.Count > 0)
{
LblCount.Text = datatable.Rows.Count + " records";
PanelResults.Visible = true;
GrvCustomResults.Visible = true;
GrvCustomResults.DataSource = datatable;
GrvCustomResults.DataBind();
}
The problem is that the query itself returns 10 rows, so the gridview will never show a pager.
<asp:GridView ID="GrvCustomResults" runat="server" Visible="false" AutoGenerateColumns="true">
<PagerSettings
Visible="true"
Position="TopAndBottom"
PreviousPageText="Previous"
NextPageText="Next"
Mode="NumericFirstLast" />
<HeaderStyle CssClass="gridheader" />
this code in aspx page
<asp:Panel runat="server" id="pnlPager" CssClass="pager">
</asp:Panel>
Here the method that will use in the .cs page
This is used to track the record of the pagenum and pagesize
protected int PageNum
{
get { return Convert.ToInt16(ViewState["PageNum"]); }
set { ViewState["PageNum"] = value; }
}
protected int PageSize
{
get { return Convert.ToInt16(ViewState["PageSize"]); }
set { ViewState["PageSize"] = value; }
}
protected int TotalRecord
{
get { return Convert.ToInt16(ViewState["TotalRecords"]); }
set { ViewState["TotalRecords"] = value; }
}
This is the method is used for the call the store procedure that will send the pagenum ,page size
public DataSet GetCollegeSerachData(int PageNum,int PageSize,out int TotalRecords)
{
DS = new DataSet();
ObjDataWrapper = new DataWrapper(ClsCommon.CnnString, CommandType.StoredProcedure);
TotalRecords=0;
ErrorCount = 0;
Searchpattern = "";
try
{
ObjDataWrapper.AddParameter("#PageNum", PageNum);
ObjDataWrapper.AddParameter("#PageSize", PageSize);
SqlParameter ObjTotalRecords=(SqlParameter)(ObjDataWrapper.AddParameter("#TotalRowsNum","",SqlDbType.Int,ParameterDirection.Output));
DS=ObjDataWrapper.ExecuteDataSet("ADMJGetCollegeSearch");
if(ObjTotalRecords.Value!= DBNull.Value || ObjTotalRecords!=null)
{
TotalRecords=Convert.ToInt32(ObjTotalRecords.Value);
}
}
catch (Exception Ex)
{
string err = Ex.Message;
if (Ex.InnerException != null)
{
err = err + " :: Inner Exception :- " + Ex.InnerException.Message;
}
string addInfo = "Error While Executing GetCollegeSerachData in ClsColleges:: -> ";
ClsExceptionPublisher objPub = new ClsExceptionPublisher();
objPub.Publish(err, addInfo);
}
return DS;
}
that will return the dataset that will used to bind the store procedure
here the store procedure that will used for pagination
GO
/****** Object: StoredProcedure [dbo].[ADMJGetCollegeSearch] Script Date: 06/06/2012 15:43:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[ADMJGetCollegeListByState]
#PageNum int,
#PageSize int,
#TotalRowsNum int output
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
WITH College_CollegeId As
(
SELECT 'RowNumber' = ROW_NUMBER() OVER(ORDER BY collegeid asc),College.*
FROM College
)
-- Query result
SELECT *
FROM College_CollegeId
WHERE RowNumber BETWEEN (#PageNum - 1) * #PageSize + 1 AND #PageNum * #PageSize
ORDER BY collegename asc
-- Returns total records number
SELECT #TotalRowsNum = count(*)
FROM College
END
at last you will bind the the gridview
grdCourse.DataSource = DS.Tables[0];
grdCourse.DataBind();
grdCourse.Visible = true;
at the PageIndexChanging(object sender, GridViewPageEventArgs e) of the grid view you will pass the
protected void grdCourse_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
Pagenum = e.NewPageIndex;
--call this method public DataSet GetCollegeSerachData(int PageNum,int PageSize,out int TotalRecords)
}

problem to save data in a SQL database from a results table via web service

I have a problem and I need your help. As my web service describes I want to get some data and add them to my database.
[WebMethod(Description = "This will input computers into the database", EnableSession = false)]
public string orderItem(int CUS_ID, string COM_ID, int Quantity,double COMPrice)
{
try
{
dbConn = new DbConnection();
SqlConnection conn = dbConn.OpenConnection();
SqlCommand orderItem = new SqlCommand("OrderComputer", conn);
orderItem.CommandType = CommandType.StoredProcedure;
SqlParameter add_CUS_ID = orderItem.Parameters.Add("#CUS_ID", SqlDbType.Int, 4);
add_CUS_ID.Value = CUS_ID;
SqlParameter addBK_ISBN = orderItem.Parameters.Add("#COM_ID", SqlDbType.Char, 80);
addBK_ISBN.Value = COM_ID;
SqlParameter add_Quantity = orderItem.Parameters.Add("#Quantity", SqlDbType.Int, 2);
add_Quantity.Value = Quantity;
SqlParameter add_COMPrice = orderItem.Parameters.Add("#COMPrice", SqlDbType.Money, 8);
add_COMPrice.Value = COMPrice;
return this.ExecuteQuery(orderItem);
}
catch (Exception e)
{
return e.ToString();
}
}
The OrderComputer is a stored procedure:
ALTER Procedure OrderComputer
(
#CUS_ID int,
#COM_ID int,
#Quantity int,
#COMPrice money
)
AS
declare #Date datetime
declare #ShipDate datetime
declare #OR_ID int
select #Date = getdate()
select #ShipDate = getdate()
begin tran NewComputer
INSERT INTO Orders
(
CUS_ID,
Date,
ShipDate
)
VALUES
(
#CUS_ID,
#Date,
#ShipDate
)
SELECT #OR_ID = ##Identity
INSERT INTO ComputerOrders
(
OR_ID,
COM_ID,
Quantity,
COMPrice
)
VALUES
(
#OR_ID,
#COM_ID,
#Quantity,
#COMPrice
)
commit tran NewComputer
The following part is the final step of my shopping cart. It returns a table with the order details. My problem is why the line
order.orderItem(customerID, Computer_ID, quantity, price);
cannot get the record to add it to the database?. Is something missing?
computerOrder1.computerOrder order = new computerOrder1.computerOrder();
int quantity = 2;
XmlDocument customer_Order = ComputerCart.getCartDescription();
while (customer_Order.SelectNodes("//Computers").Count > 0)
{
string Computer_ID = customer_Order.GetElementsByTagName("Computers").Item(0).SelectSingleNode("//com_id").InnerText;
double price = double.Parse(customer_Order.GetElementsByTagName("Computers").Item(0).SelectSingleNode("//price").InnerText);
string Model = customer_Order.GetElementsByTagName("Computers").Item(0).SelectSingleNode("//model").InnerText;
order.orderItem(customerID, Computer_ID, quantity, price);
}
Juding by your comment:
protected string ExecuteQuery(SqlCommand QueryObject) {
int queryResult = QueryObject.ExecuteNonQuery();
if (queryResult != 0) {
return "Your request is CORRECT";
}
else {
return "error: QueryResult= " + queryResult;
}
}
You would need not only your SqlCommand but also your connection
protected string ExecuteQuery(SqlCommand QueryObject, SqlConnection conn) {
try
{
conn.open();
int queryResult = QueryObject.ExecuteNonQuery();
if (queryResult != 0) {
return "Your request is CORRECT";
}
else {
return "error: QueryResult= " + queryResult;
}
}
finally
{
conn.close();
}
}

Categories

Resources