I have a function like this
///
/// This function binds the emplist drop down for mentor user.
///
private void BindEmpDropDownForMentor()
{
string strSelectMentorQuery = "SELECT FIRST_NAME + ' ' + LAST_NAME AS NAME FROM M_USER_DETAILS MUD INNER JOIN M_LEADERLED MLL "
+ "ON MLL.LED_ID = MUD.PK_ID WHERE MLL.LEADER_ID = '" + Session["UserID"].ToString()
+ "' AND MUD.ACTIVE = 1 AND MLL.START_DATE <= Getdate() AND"
+ " MLL.END_DATE > Getdate()";
OleDbConnection oleConnection = new OleDbConnection(ConfigurationSettings.AppSettings["SQLConnectionString"]);
OleDbCommand oleCommand = new OleDbCommand(strSelectMentorQuery, oleConnection);
try
{
//Open Connection
oleConnection.Open();
//Set Datasource and close connection
cmbempList.DataSource = oleCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
cmbempList.DataValueField = "";
cmbempList.DataTextField = "NAME";
//Bind the Dropdown
cmbempList.DataBind();
//Add a new item 'ALL TEAM MEMBERS' to the member list
cmbempList.Items.Insert(0, new ListItem("ALL TEAM MEMBERS", "0"));
cmbempList.SelectedIndex = 0;
GridViewDataShowBy = cmbempList.SelectedValue;
}
catch (Exception ex)
{
ExceptionLogger.LogException(ex);
}
finally
{
// Close the connection when done with it.
oleConnection.Close();
}
}
But on selected change event of cmbempList, format exception error is being caught saying this that input string was not in correct form in the bold line below
protected void cmbempList_SelectedIndexChanged(object sender, EventArgs e)
{
gvLeaveList.CurrentPageIndex = 0;
dgDaysAbsent.CurrentPageIndex = 0;
**if (!(Convert.ToInt32(cmbempList.SelectedValue) > 0))
{**
if (this.Session["RoleID"].ToString() == "1")
{
cmbLeads.ClearSelection();
cmbLeads.SelectedIndex = cmbLeads.Items.IndexOf(cmbLeads.Items.FindByValue(this.Session["UserID"].ToString()));
}
}
GridViewDataShowBy = cmbempList.SelectedValue.ToString();
if (cmbempList.SelectedValue != "0" && cmbempList.SelectedValue != "")
{
Page.Title = cmbempList.SelectedItem.Text + " | Leave List | "
+ OrganizationManager.GetCurrentOrganizationName(Session["OrgID"]);
}
else
{
Page.Title = "Leave List | "
+ OrganizationManager.GetCurrentOrganizationName(Session["OrgID"]);
}
PopulateLeaveList(GridViewDataShowBy, "0");
BindLeaveListGrid(GridViewDataShowBy, cmbLeads.SelectedValue.ToString());
}
It is because cmbempList's DataValueField is being set to an empty string in the BindEmpDropDownForMentor method.
cmbempList.DataValueField = "";
This will cause cmbempList's values to be bound to the values in the DataTextField which are strings. When the SelectedIndexChange event is called it tries to parse the strings to an Int32 which is throwing the exception.
Convert.ToInt32(cmbempList.SelectedValue) > 0
To fix it you can add an aliased ID field in the SQL query and set the cmbempList.DataValueField to that ID name which is probably your intent.
For example in BindEmpDropDownForMentor make this edit to your query:
string strSelectMentorQuery = "SELECT FIRST_NAME + ' ' + LAST_NAME AS NAME, MLL.LED_ID AS ID FROM M_USER_DETAILS MUD INNER JOIN M_LEADERLED MLL "
+ "ON MLL.LED_ID = MUD.PK_ID WHERE MLL.LEADER_ID = '" + Session["UserID"].ToString()
+ "' AND MUD.ACTIVE = 1 AND MLL.START_DATE <= Getdate() AND"
+ " MLL.END_DATE > Getdate()";
And assign your DataValueField to this:
cmbempList.DataValueField = "ID";
try this.
if it still fails look in the debugger what value cmbempList.SelectedValue contains.
protected void cmbempList_SelectedIndexChanged(object sender, EventArgs e)
{
// ...
object selectedValue = cmbempList.SelectedValue;
if ((selectedValue != null) && (selectedValue != DBNull.Value) && (!(Convert.ToInt32(selectedValue) > 0))
{
// ...
Related
I have created a payment in Checks and Payments screen of Acumatica screen and released it. Please refer to the following screenshot.
I've already create the following code to provide it.
protected virtual void APPayment_RowPersisted(PXCache sender, PXRowPersistedEventArgs e)
{
string serverJade, dbJade, userJade, passJade;
serverJade = Properties.Settings.Default.serverJade;
dbJade = Properties.Settings.Default.dbJade;
userJade = Properties.Settings.Default.userJade;
passJade = Properties.Settings.Default.passJade;
APPayment app = (APPayment)e.Row;
if (e.Operation == PXDBOperation.Update && e.TranStatus == PXTranStatus.Completed)
{
if (app.DocType == APPaymentType.Check || app.DocType == APPaymentType.Prepayment)
{
if (app.RefNbr != null)
{
using (SqlConnection con = new SqlConnection("server = " + serverJade + "; database = " + dbJade + "; user = " + userJade + "; password = " + passJade + ""))
{
con.Open();
//---- query to update a field in the table of another database -------//
string query = "Update EVMaster set AcuRefNo = '" + app.RefNbr + "' where VchNo = 'DD02/16-VIII/12206-VCH-01'";
using (SqlCommand com = new SqlCommand(query, con))
{
SqlDataReader sdr = com.ExecuteReader();
sdr.Close();
}
con.Close();
}
}
}
}
}
I already tried to debug this code, but didn't work. And then I try to use this follwing code.
protected virtual void APPayment_RowPersisted(PXCache sender, PXRowPersistedEventArgs e)
{
string serverJade, dbJade, userJade, passJade;
serverJade = Properties.Settings.Default.serverJade;
dbJade = Properties.Settings.Default.dbJade;
userJade = Properties.Settings.Default.userJade;
passJade = Properties.Settings.Default.passJade;
APPayment app = (APPayment)e.Row;
if (app.DocType == APPaymentType.Check || app.DocType == APPaymentType.Prepayment)
{
if (app.RefNbr != null)
{
using (SqlConnection con = new SqlConnection("server = " + serverJade + "; database = " + dbJade + "; user = " + userJade + "; password = " + passJade + ""))
{
con.Open();
//---- query to update a field in the table of another database -------//
string query = "Update EVMaster set AcuRefNo = '" + app.RefNbr + "' where VchNo = 'DD02/16-VIII/12206-VCH-01'";
using (SqlCommand com = new SqlCommand(query, con))
{
SqlDataReader sdr = com.ExecuteReader();
sdr.Close();
}
con.Close();
}
}
}
}
The codes above is worked, I just remove the if condition (if (e.Operation == PXDBOperation.Update && e.TranStatus == PXTranStatus.Completed)
{}).
But it's not my goal, I have to filter document only for Doc Status = 'printed' from the document, and this process will be executed when 'Release' button was clicked.
And also any idea how to get all records in APAdjust of the current document ? because I need to comparing adjgrefnbr in apadjust with refnbr in APInvoice based on adjgrefnbr (apadjust) = refnbr (apinvoice). So I can get also all records of APinvoice based on refnbr (APinvoice) = ajgrefnbr (current apadjust). This condition is used to make 'where' condition of query not have to be hardcoded, I will used variable to provide it.
any suggestions to sove this problem ?
Below is an example showing how to extend Release process for checks and subscribe to RowPersisted handler for the APRegister DAC to save released document RefNbr to another database:
public class APPaymentEntryExt : PXGraphExtension<APPaymentEntry>
{
public PXAction<APPayment> release;
[PXUIField(DisplayName = "Release", MapEnableRights = PXCacheRights.Update, MapViewRights = PXCacheRights.Update)]
[PXProcessButton]
public IEnumerable Release(PXAdapter adapter)
{
PXGraph.InstanceCreated.AddHandler<APReleaseProcess>((graph) =>
{
graph.RowPersisted.AddHandler<APRegister>(APReleaseCheckProcess.APPaymentRowPersisted);
});
return Base.release.Press(adapter);
}
}
public class APReleaseChecksExt : PXGraphExtension<APReleaseChecks>
{
protected virtual void ReleaseChecksFilter_RowSelected(PXCache sender, PXRowSelectedEventArgs e)
{
var row = e.Row as ReleaseChecksFilter;
if (row == null) return;
Base.APPaymentList.SetProcessDelegate(list =>
{
PXGraph.InstanceCreated.AddHandler<APReleaseProcess>((graph) =>
{
graph.RowPersisted.AddHandler<APRegister>(APReleaseCheckProcess.APPaymentRowPersisted);
});
APReleaseChecks.ReleasePayments(list, row.Action);
});
}
}
By executing quite simple BQL query you can access APAdjust records associated with released check within handler for the RowPersisted event:
public static class APReleaseCheckProcess
{
public static void APPaymentRowPersisted(PXCache sender, PXRowPersistedEventArgs e)
{
if (e.TranStatus == PXTranStatus.Completed && e.Operation == PXDBOperation.Update)
{
var doc = e.Row as APPayment;
if (doc != null && doc.Released == true)
{
// save RefNbr to another database
foreach (APAdjust oldadj in PXSelect<APAdjust,
Where<
APAdjust.adjgDocType, Equal<Required<APPayment.docType>>,
And<APAdjust.adjgRefNbr, Equal<Required<APPayment.refNbr>>,
And<APAdjust.adjNbr, Less<Required<APPayment.lineCntr>>>>>>
.Select(sender.Graph, doc.DocType, doc.RefNbr, doc.LineCntr))
{
}
}
}
}
}
I have 3 Tables
LaminationTitle**
LaminationTitleRelation
Papertypemaster
I Want to update Values of"LaminationTitleRelation" table which comes from CheckboxList... Below is my Update Form....
Lamination Title in Below form Updated in LaminationTitle Table, where as
Checkbox List Items should Update in LaminationTitleRelation Table
Note: if "Papertypeid" in LaminationTitleRelation and Items Checked are different then it should be add.
Plz help me
Use the following query:
query = "Create Table #PaperTypeMapping(LaminationTitleId int, PaperTypeId int)";
//For each value of Paper Type Id you will need to insert a row
query = "Insert Into #PaperTypeMapping(LaminationTitleId, PaperTypeId) Values(#laminationId, #paperTypeId)";
//Update existing values
query = "Update OldMapping Set OldMapping.ActiveStatus = 1 FROM LaminationTitleRelation OldMapping Inner join #PapertTypeMapping NewMapping ON OldMapping.LamTitleId = NewMapping.LaminationTitleId and OldMapping.PaperTypeId = NewMapping.PaperTypeId"
//Insert new values
query = "Insert into LaminationTitleRelation(lamTitleId, PapertTypeId, ActiveStatus) Select LaminationTitleId, PapertTYpeId, 1 From #PaperTypeMapping NewMapping where NOT EXISTS(SELECT 1 FROM LaminationTitleRelation OldMapping WHERE OldMapping.LamTitleId = NewMapping.LaminationTitleId and OldMapping.PaperTypeId = NewMapping.PaperTypeId)";
or alternatively you can use the following link a built in utility by MS SQL Merge
protected void btnUpdate_Click(object sender, EventArgs e) {
DB = new DBFunctions();
string vItems = mGetSelectedItems();
string vQuery = "Update laminationtitle Set title='" + txtLaminationTitle.Text + "',laminationtypeid='" + ddlProductType.SelectedValue + "' where laminationid='" + Request.QueryString["laminationid"] + "'";
int x = DB.SetData(vQuery);
DataTable dSelect = new DataTable();
DataTable dAll = new DataTable();
DB = new DBFunctions();
DB1 = new DBFunctions();
if (x > 0) {
int y = DB.SetData("delete from laminationtitlepapertyperelation where lamtitleid=" + Request.QueryString["laminationid"]);
if (y > 0) {
string[] values = vItems.Split(',');
for (int i = 0; i < values.Length; i++) {
vQuery = "insert into laminationtitlepapertyperelation(lamtitleid, papertypeid, activestatus)VALUES('" + Request.QueryString["laminationid"].ToString() + "','" + values[i] + "',1)";
DB.SetData(vQuery);
ScriptManager.RegisterStartupScript(this, GetType(), " Update Lamination Title", "alert('Lamination " + '"' + txtLaminationTitle.Text + '"' + " Title Updated Sucessfully');window.location='ManageLaminationTitle.aspx';", true);
}
}
}
}
I am trying to make this code work fine as i can but i couldnt,i am using cookie and i want to rebind my ListView depending on cookie Location but i am getting error message: "Must declare the scalar variable "#Location"."
protected void Sortcarbtn_Click(object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies.Get("Location");
using (SqlConnection carcon = new SqlConnection(ConfigurationManager.ConnectionStrings["BeravaConnectionString"].ConnectionString))
if (cookie != null)
{
string CarSqlST = #"SELECT DISTINCT AdsID, Section, Category, Country, Maker, Gear, Condition, Status, State, City, AdsTit,
SUBSTRING(AdsDesc,1,155) as AdsDesc, Year, AdsPrice, Img1 From ads Where 1=1 AND Category=#CATE AND Country = #Location ";
var Location = Convert.ToString(cookie["Location"]);
var cat = Convert.ToString(Request.QueryString["cat"]);
string condition = "";
if (barndcardrlst.SelectedValue != "")
{
condition += " and Maker='" + barndcardrlst.SelectedValue + "'";
}
if (GearDrDw.SelectedValue != "")
{
condition += " and Gear='" + GearDrDw.SelectedValue + "'";
}
if (carstatedrdolst.SelectedValue != "")
{
condition += " and State='" + carstatedrdolst.SelectedValue + "'";
}
if (citiesdrdolst.SelectedValue != "")
{
condition += " and City='" + citiesdrdolst.SelectedValue + "'";
}
if (CarCondDrDw.SelectedValue != "")
{
condition += " and Condition='" + CarCondDrDw.SelectedValue + "'";
}
if (CarstusDRDL.SelectedValue != "")
{
condition += " and Status='" + CarstusDRDL.SelectedValue + "'";
}
if ((CarPriceFrmDrDw.SelectedValue != "") && (CarPriceToDrDw.SelectedValue != ""))
{
condition += " and AdsPrice BETWEEN " + CarPriceFrmDrDw.SelectedValue + " AND " + CarPriceToDrDw.SelectedValue;
}
if ((CarYearfrmDrDw.SelectedValue != "") && (CarYeartoDrDw.SelectedValue != ""))
{
condition += " and Year BETWEEN " + CarYearfrmDrDw.SelectedValue + " AND " + CarYeartoDrDw.SelectedValue;
}
DataTable cdt = new DataTable();
carcon.Open();
SqlCommand ccmd = new SqlCommand();
ccmd.Connection = carcon;
ccmd.CommandType = CommandType.Text;
ccmd.Parameters.AddWithValue("#Country", Location);
ccmd.Parameters.AddWithValue("#CATE", cat);
ccmd.CommandText = CarSqlST + condition;
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = ccmd;
ad.Fill(cdt);
cateshowlistview.DataSource = cdt;
cateshowlistview.DataBind();
}
}
Change "#Country" in
ccmd.Parameters.AddWithValue("#Country", Location);
to be "#Location"
ccmd.Parameters.AddWithValue("#Location", Location);
you defined the Country in the SQL Statement to be #Location
string CarSqlST = #"SELECT ... AND Category=#CATE AND Country = #Location ";
Update
To prevent SQL Injection hacks and to allow for SQL to reuse the query options all the fileters where you are concat the string together you should just use SQL Parameters. To make it easy I create a parameters dictionary to add to. Then at the end loop through the dictionary to fill in the SQL Parameters. I also switched it to string builder since could be doing a lot of string concats. I didn't test this code because I don't have your objects or tables or connections.
using (var carcon = new SqlConnection(ConfigurationManager.ConnectionStrings["BeravaConnectionString"].ConnectionString)))
{
if (cookie != null)
{
// Parameters for SQL
var parameters = new Dictionary<string, object>();
// string builder to build up SQL Statement
var CarSqlST = new StringBuilder(
"SELECT DISTINCT AdsID, Section, Category, Country, Maker, Gear, Condition, Status, State, City, AdsTit, " +
"SUBSTRING(AdsDesc,1,155) as AdsDesc, Year, AdsPrice, Img1 From ads " +
"Where Category = #pCATE AND Country = #pLocation ");
parameters.Add("#pCATE", Request.QueryString["cat"].ToString());
parameters.Add("#pLocation", cookie["Location"]);
if (barndcardrlst.SelectedValue != "")
{
CarSqlST.Append(" and Maker= #pMaker");
parameters.Add("#pMaker", barndcardrlst.SelectedValue);
}
if (GearDrDw.SelectedValue != "")
{
CarSqlST.Append(" and Gear= #pGear");
parameters.Add("#pGear", GearDrDw.SelectedValue);
}
if (carstatedrdolst.SelectedValue != "")
{
CarSqlST.Append(" and State= #pState");
parameters.Add("#pState", carstatedrdolst.SelectedValue);
}
if (citiesdrdolst.SelectedValue != "")
{
CarSqlST.Append(" and State= #pCity");
parameters.Add("#pCity", citiesdrdolst.SelectedValue);
}
if (CarCondDrDw.SelectedValue != "")
{
CarSqlST.Append(" and Condition= #pCondition");
parameters.Add("#pCondition", CarCondDrDw.SelectedValue);
}
if (CarstusDRDL.SelectedValue != "")
{
CarSqlST.Append(" and Status= #pStatus");
parameters.Add("#pStatus", CarstusDRDL.SelectedValue);
}
if ((CarPriceFrmDrDw.SelectedValue != "") && (CarPriceToDrDw.SelectedValue != ""))
{
CarSqlST.Append(" and AdsPrice BETWEEN #pLowPrice AND #pHighPrice");
parameters.Add("#pLowPrice", CarPriceFrmDrDw.SelectedValue);
parameters.Add("#pHighPrice", CarPriceToDrDw.SelectedValue);
}
if ((CarYearfrmDrDw.SelectedValue != "") && (CarYeartoDrDw.SelectedValue != ""))
{
CarSqlST.Append(" and Year BETWEEN #pLowYear AND #pHighYear");
parameters.Add("#pLowYear", CarYearfrmDrDw.SelectedValue);
parameters.Add("#pHighYear", CarYeartoDrDw.SelectedValue);
}
DataTable cdt = new DataTable();
SqlCommand ccmd = carcon.CreateCommand();;
ccmd.CommandType = CommandType.Text;
// Add all the parameters into this command
foreach (var parameter in parameters)
{
ccmd.Parameters.Add(parameter.Key, parameter.Value);
}
// set the command text from string builder
ccmd.CommandText = CarSqlST.ToString();
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = ccmd;
}
}
You could have created the command at the top and filled in the sql parameters right away instead of the dictionary but I like the dictionary approach better in case something happens - exception or we need to bail we never created the SQL Command.
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.
I have a problem with the collectionpager and repeater. When I load the page, collectionpager is working fine.. But when I click the search button and bind new data, clicking the page 2 link, it is firing the page_load event handler and bring all the data back again... Notice: All controls are in an UpdatePanel.
protected void Page_Load(object sender, EventArgs e){
if (!IsPostBack)
{
kayit_getir("SELECT Tbl_Icerikler.ID,Tbl_Icerikler.url,Tbl_Icerikler.durum,Tbl_Icerikler.baslik,Tbl_Icerikler.gunc_tarihi,Tbl_Icerikler.kayit_tarihi,Tbl_Icerikler.sira,Tbl_Kategoriler.kategori_adi FROM Tbl_Icerikler,Tbl_Kategoriler where Tbl_Kategoriler.ID=Tbl_Icerikler.kategori_id ORDER BY Tbl_Icerikler.ID DESC,Tbl_Icerikler.sira ASC");
}}
public void kayit_getir(string SQL){
SqlConnection baglanti = new SqlConnection(f.baglan());
baglanti.Open();
SqlCommand komut = new SqlCommand(SQL, baglanti);
SqlDataAdapter da = new SqlDataAdapter(komut);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
CollectionPager1.DataSource = dt.DefaultView;
CollectionPager1.BindToControl = Liste;
Liste.DataSource = CollectionPager1.DataSourcePaged;
}
else
{
kayit_yok.Text = "<br /><span class='message information'>Kayıt bulunamadı.</span>";
}
da.Dispose();
baglanti.Close();
CollectionPager1.DataBind();
Liste.DataBind();}
protected void search_Click(object sender, EventArgs e){
string adi = f.temizle(baslik.Text);
string durum = Durum.SelectedValue;
string kayit_bas_t = kayit_bas_tarih.Text;
string kayit_bit_t = kayit_bit_tarih.Text;
string kategori = kategori_adi.SelectedValue;
string SQL = "SELECT Tbl_Icerikler.ID,Tbl_Icerikler.url,Tbl_Icerikler.durum,Tbl_Icerikler.baslik,Tbl_Icerikler.gunc_tarihi,Tbl_Icerikler.kayit_tarihi,Tbl_Icerikler.sira,Tbl_Kategoriler.kategori_adi FROM Tbl_Icerikler,Tbl_Kategoriler where Tbl_Kategoriler.ID=Tbl_Icerikler.kategori_id and";
if (adi != "")
{
SQL = SQL + " Tbl_Icerikler.baslik LIKE '%" + adi + "%' and";
}
if (kategori != "")
{
SQL = SQL + " Tbl_Icerikler.kategori_id=" + kategori + " and";
}
if (durum != "")
{
SQL = SQL + " Tbl_Icerikler.durum='" + durum + "' and";
}
if (kayit_bas_t != "")
{
SQL = SQL + " (Tbl_Icerikler.kayit_tarihi>'" + kayit_bas_t + "') and";
}
if (kayit_bit_t != "")
{
SQL = SQL + " (Tbl_Icerikler.kayit_tarihi<'" + kayit_bit_t + "') and";
}
SQL = SQL.Remove(SQL.Length - 3, 3);
SQL = SQL + " ORDER BY sira ASC,ID DESC";
try
{
kayit_getir(SQL);
}
catch { }
Recursive(0, 0);}
the code is very bad and you should completely review all of it.
the issue is every time the page load is executed it initializes again you query to the default one (the one with not filter) you should find a way to store somewhere the last query has been execute when you order/filtering your data.
Anyway the are lot of example on the web showing what you are trying to achieve
the below is just one of them
http://www.codeproject.com/KB/webforms/ExtendedRepeater.aspx
try this EnableViewState="false"
You have to bind the CollectionPager again on your search.