Quantcast
Channel: Access Databases and AccessDataSource Control
Viewing all 518 articles
Browse latest View live

IF EXISTS ALTERNATIVE IN ASP.NET/C#, USING ACCESS DATABASE

$
0
0

Hi, i'm creating a shopping Cart using an Access Database, but when it comes to update or add some product in the shopping cart i had to do some verification, but Access doesn't accept the if exists statement in his sql code. How can i write it otherwise using C# while i'm using a System.Data.Common(DbCommand, DbParameter...)? here is my sql code:

CREATE PROCEDURE ShoppingCartAjoutProduits
(@CartID char(36),
@ProduitID int,
@Attributs char(255))
As
IF EXISTS
(SELECT CartID
FROM ShoppingCart
WHERE ProduitID = @ProduitID AND CartID = @CartID)
UPDATE ShoppingCart
SET Quantite = Quantite + 1
WHERE ProduitID = @ProduitID AND CartID = @CartID
ELSE
IF EXISTS (SELECT titre FROM livres WHERE NumLivre = @NumLivre)
INSERT INTO ShoppingCart (CartID, ProduitID, Attributs, Quantite, DateAjoute)
VALUES (@CartID, @ProduitID, @Attributs, 1, GETDATE())

thanks


Help Sintaxis Error on Update Statement

$
0
0

Hi I need Help Im trying to update from a gridview but when I insert the data on click Update its giving me a 

System.Data.OleDb.OleDbException was unhandled by user code
HResult=-2147217900
Message=Syntax error in UPDATE statement.
Source=Microsoft Office Access Database Engine
ErrorCode=-2147217900
StackTrace:
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
at System.Web.UI.WebControls.SqlDataSourceView.ExecuteDbCommand(DbCommand command, DataSourceOperation operation)
at System.Web.UI.WebControls.SqlDataSourceView.ExecuteUpdate(IDictionary keys, IDictionary values, IDictionary oldValues)
at System.Web.UI.WebControls.SqlDataSource.Update()
at _Default.GridView1_RowUpdating(Object sender, GridViewUpdateEventArgs e) in c:\Users\ITMANAGER\Documents\Visual Studio 2012\Projects\Nova\Nova\Company_menu\receiving_update.aspx.cs:line 209
at System.Web.UI.WebControls.GridView.OnRowUpdating(GridViewUpdateEventArgs e)
at System.Web.UI.WebControls.GridView.HandleUpdate(GridViewRow row, Int32 rowIndex, Boolean causesValidation)
at System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup)
at System.Web.UI.WebControls.GridView.OnBubbleEvent(Object source, EventArgs e)
at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
at System.Web.UI.WebControls.GridViewRow.OnBubbleEvent(Object source, EventArgs e)
at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
at System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e)
at System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument)
at System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException:

heres is the code 

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Get the values stored in the text boxes
string strCompanyName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCompany_Name")).Text;
string strReceivedfrom = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtRECEIVED_FROM")).Text;
string strShipTo = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtSHIP_TO")).Text;
string strDate = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtDATE")).Text;
string strPO = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtPO")).Text;
string strBLN = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtBLN")).Text;
string strShipVia = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtSHIP_VIA")).Text;
string strWO = ((Label)GridView1.Rows[e.RowIndex].FindControl("lblWO")).Text;
string strInVoice_date = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtINVOICE_DATE")).Text;
string strMx = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtDATE_MX")).Text;
string strTrailer = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtTRAILER")).Text;
string strTo = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtTO")).Text;

//Prepare the Update Command of the DataSource control
string strSQL = "";
strSQL = "UPDATE NEWRECEIVE SET COMPANY_NAME = '" + strCompanyName + "'" +
",RECEIVED_FROM = '" + strReceivedfrom + "'" +
",SHIPTO = '" + strShipTo + "'" +
",DATE_RECEIVED = '" + DateTime.Parse (strMx) + "'" +
",PO = '" + strPO + "'" +
",BLN = '" + strBLN + "'" +
",SHIP_VIA = '" + strShipVia + "'" +
",INVOICE_DATE = '" + DateTime.Parse(strInVoice_date) + "'" +
",DATE_MX = '" + DateTime.Parse(strMx)+ "'" +
",TRAILER = '" + strTrailer + "'" +
",TO = '" + strTo + "'" +
" WHERE WO = '" + strWO + "'";

AccessDataSource1.UpdateCommand = strSQL;
AccessDataSource1.Update();

thanks 

Inconsistent Error Message

$
0
0

I have a page that works 3/4 of the time and then every once in a while it throws an error message.  The error message is at a place in the code where the SQL is executed:

dbreadTWO = dbcommTWO.ExecuteReader()

I have several subroutines and the error will land on the same line of one of them... until I disable that subroutine.  Then it will land on the line referencing the code above on a different subroutine.  But, as I say, there is no error at all about 75% of the time.  I will refresh, refresh, refresh, error, then refresh, refresh, refresh, etc.

The error text itself also is not consistent!  I've gotten the following:

System.Data.OleDb.OleDbException: Unknown

Invalid SQL syntax - related tokens did not match. The Microsoft Access database engine expected GRANT...TO, REVOKE...FROM, ADD...TO, or DROP...FROM.

Unspecified error: DB_E_ERRORSINCOMMAND(0x80040E14)

The delete option is not allowed because a child record still exists

I am connecting to the DB like this:

<div>

<add name="WMConnectionString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\192.168.0.150\data\Webmaster2011.accdb;" providerName="System.Data.OleDb" />

The SQLs are all simple SELECTs -- I am not inserting or updating or deleting or anything like that.

I know that access is rotten, etc., -- I have no choice but to work with access right now.

Any ideas?  I have no idea how to troubleshoot with something so random!

Tracking URL in table

$
0
0
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><%@ Register assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" namespace="System.Web.UI.WebControls" tagprefix="asp" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><title>Order Tracking Online</title><link href="StyleSheet.css" rel="stylesheet" type="text/css" /><style type="text/css">
        .style1
        {
            width: 293px;
            margin-right: 202px;
        }
        .style3
        {
            width: 338px;
            height: 83px;
        }
        .style4
        {
            width: 338px;
            height: 120px;
        }
        .style5
        {
            width: 338px;
            height: 27px;
        }
        .formRow .fieldLabel, .formRow .fieldLabelBold, .formRowError .fieldLabel, .formRow .fieldLabelBold { color: #333; float: left;  font-weight: bold; margin:0; padding:0; width: 140px; text-transform: uppercase; }

.fieldLabel {width: 150px;}
        .style8
        {
            width: 166%;
        }
        .style14
        {
            width: 271px;
            height: 90px;
        }
        .style15
        {
            width: 10px;
            height: 90px;
        }
        .style16
        {
            height: 90px;
        }
        .style17
        {
        }
        .style19
        {
            width: 10px;
        }
        .postcode
        {
            text-transform: uppercase;
        }
        .style20
        {
            width: 338px;
            height: 378px;
        }
        .style21
        {
            width: 26px;
            height: 29px;
        }
    </style><script language="javascript" type="text/javascript">
// <![CDATA[

        function Submit1_onclick() {

        }

        function OrderID_onclick() {

        }

        function Text2_onclick() {

        }

// ]]></script></head><body><form id="form1" runat="server"><table cellpadding="4" cellspacing="5" class="style1"><tr class="Header"><td class="style3"><img alt="Track My Order" border="0" class="Header" name="Track My Order"
                    src="images/header_tmo_en.jpg" title="Track My Order" /></td><td class="style3">&nbsp;</td><td class="style3">&nbsp;</td></tr><tr><td class="style4"><p class="welcome">
                    Once you have submitted your order, you will receive an order confirmation by
                    email to confirm that your order has been received. This email will contain your<strong>order number</strong>, which along with the <strong>post code of your
                    shipping address</strong>, will be all you need to track your order.<br /><br />
                    To view your order status online, please enter your order number and the post
                    code of your shipping address:</p></td><td class="style4">&nbsp;</td><td class="style4">&nbsp;</td></tr><tr class="trackingboxH1"><td class="style5" title="Get your Order ID">
                ORDER ID<label class="fieldLabel" for="OrderID">&nbsp; #:<asp:TextBox
                    ID="orderId" runat="server"></asp:TextBox></label><br /><br />
                POST CODE#:&nbsp;<asp:TextBox ID="postcode" runat="server" CssClass="postcode"></asp:TextBox>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input id="Submit1" type="submit" value="Track"
                    onclick="return Submit1_onclick()" readonly="readonly" /><br /><br /><img alt="ID " class="style21" src="images/exp.jpg" />&nbsp; Dont Know your
                order id? <a href="get_your_id.aspx">Click here</a></td><td class="style5">&nbsp;</td><td class="style5">&nbsp;</td></tr><tr class="data"><td class="style20"><table class="style8"><tr><td class="style14"><br /><asp:DetailsView ID="DetailsView2" runat="server" AutoGenerateRows="False"
                                DataKeyNames="OrderNo" DataSourceID="AccessDataSource2" Height="50px"
                                Width="271px" BackColor="White" BorderColor="#E7E7FF" BorderStyle="None"
                                BorderWidth="1px" CellPadding="3" GridLines="None"><AlternatingRowStyle BackColor="#F7F7F7" /><EditRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" /><Fields><asp:BoundField DataField="OrderNo" HeaderText="Order No:" InsertVisible="False"
                                        ReadOnly="True" SortExpression="OrderNo" /><asp:BoundField DataField="PayPalRef" HeaderText="Paypal Ref No:"
                                        SortExpression="PayPalRef" /><asp:BoundField DataField="PostCode" HeaderText="PostCode"
                                        SortExpression="PostCode" Visible="False" /></Fields><FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" /><HeaderStyle BackColor="White" Font-Bold="True" ForeColor="#333333" /><HeaderTemplate>
                                    Order Information</HeaderTemplate><PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" /><RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" /></asp:DetailsView><asp:AccessDataSource ID="AccessDataSource2" runat="server"
                                DataFile="/track/App_Data/orders.mdb"
                                SelectCommand="SELECT [OrderNo], [PayPalRef], [PostCode] FROM [Data] WHERE (([OrderNo] = ?) AND ([PostCode] = ?))"><SelectParameters><asp:ControlParameter ControlID="orderId" Name="OrderNo" PropertyName="Text"
                                        Type="Int32" /><asp:ControlParameter ControlID="postcode" Name="PostCode" PropertyName="Text"
                                        Type="String" /></SelectParameters></asp:AccessDataSource></td><td class="style15"></td><td class="style16"><asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False"
                                DataKeyNames="OrderNo" DataSourceID="AccessDataSource1" Height="50px"
                                Width="216px" GridLines="None"
                                onpageindexchanging="DetailsView1_PageIndexChanging1"><Fields><asp:BoundField DataField="Status" HeaderText="Your Order:"
                                        SortExpression="Status" ><HeaderStyle Font-Bold="True" Font-Size="Medium" ForeColor="#FF9900" /><ItemStyle Font-Bold="True" Font-Size="Medium" ForeColor="#FF9900" /></asp:BoundField><asp:BoundField DataField="OrderNo" HeaderText="OrderNo" InsertVisible="False"
                                        ReadOnly="True" SortExpression="OrderNo" Visible="False" /><asp:BoundField DataField="PostCode" HeaderText="PostCode"
                                        SortExpression="PostCode" Visible="False" /></Fields></asp:DetailsView><asp:AccessDataSource ID="AccessDataSource1" runat="server"
                                DataFile="/track/App_Data/orders.mdb"
                                SelectCommand="SELECT [Status], [OrderNo], [PostCode] FROM [Data] WHERE (([OrderNo] = ?) AND ([PostCode] = ?))"><SelectParameters><asp:ControlParameter ControlID="orderId" Name="OrderNo" PropertyName="Text"
                                        Type="Int32" /><asp:ControlParameter ControlID="postcode" Name="PostCode" PropertyName="Text"
                                        Type="String" /></SelectParameters></asp:AccessDataSource></td></tr><tr><td class="style17">&nbsp;</td><td class="style19">&nbsp;</td><td>&nbsp;</td></tr><tr><td class="style17" colspan="3"><asp:DetailsView ID="DetailsView3" runat="server" AutoGenerateRows="False"
                                BackColor="White" BorderStyle="None" CellPadding="3" DataKeyNames="OrderNo"
                                DataSourceID="AccessDataSource3" GridLines="None" Height="50px" Width="523px"><AlternatingRowStyle BackColor="#CCCCCC" /><EditRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" /><Fields><asp:BoundField DataField="OrderDate" HeaderText="Order Date:"
                                        SortExpression="OrderDate" /><asp:BoundField DataField="Name" HeaderText="Name:"
                                        SortExpression="Name" /><asp:BoundField DataField="Address" HeaderText="Address:"
                                        SortExpression="Address" /><asp:BoundField DataField="PostCode" HeaderText="Post Code:"
                                        SortExpression="PostCode" /><asp:BoundField DataField="EmailAddress" HeaderText="Email Address:"
                                        SortExpression="EmailAddress" /><asp:BoundField DataField="ItemNumber" HeaderText="Item Number:"
                                        SortExpression="ItemNumber" /><asp:BoundField DataField="Item" HeaderText="Product Description:"
                                        SortExpression="Item" /><asp:BoundField DataField="OrderComments" HeaderText="Order Comments:"
                                        SortExpression="OrderComments" /><asp:BoundField DataField="DeliveryDate" HeaderText="Expected Delivery Date:"
                                        SortExpression="DeliveryDate" /><asp:BoundField DataField="ExpectedTime" HeaderText="Expected Time:"
                                        SortExpression="ExpectedTime" /><asp:BoundField DataField="Courier" HeaderText="Courier"
                                        SortExpression="Courier" /><asp:BoundField DataField="CourierStatus" HeaderText="Courier Status:"
                                        SortExpression="CourierStatus" /><asp:HyperLinkField DataTextField="CourierTrackingNumber"
                                        HeaderText="Courier Tracking Data:" NavigateUrl="{0}"
                     Text="Tracking Info" DataNavigateUrlFields="CourierTrackingNumber"
                                        SortExpression="CourierTrackingNumber" ><ItemStyle Font-Size="10pt" Font-Strikeout="False" /></asp:HyperLinkField></Fields><FooterStyle BackColor="#CCCCCC" /><HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" /><PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" /></asp:DetailsView><asp:AccessDataSource ID="AccessDataSource3" runat="server"
                                DataFile="/track/App_Data/orders.mdb"
                                SelectCommand="SELECT [OrderNo], [OrderDate], [Name], [Address], [PostCode], [EmailAddress], [ItemNumber], [Item], [OrderComments], [DeliveryDate], [ExpectedTime], [Status], [Courier], [CourierStatus], [CourierTrackingNumber] FROM [Data] WHERE (([OrderNo] = ?) AND ([PostCode] = ?))"><SelectParameters><asp:ControlParameter ControlID="orderId" Name="OrderNo" PropertyName="Text"
                                        Type="Int32" /><asp:ControlParameter ControlID="postcode" Name="PostCode" PropertyName="Text"
                                        Type="String" /></SelectParameters></asp:AccessDataSource><br /></td></tr></table></td><td class="style20">&nbsp;</td><td class="style20">&nbsp;</td></tr></table></form></body></html>



Hi I have  created a Tracking site for my ebay items, ect on my site. When I send a Parcel I am given a link to access the tracking information, I would like to give users this link.

All my data is held in a Microsoft Access Table called data. There is a Colum in there caleld tracking in so I have added the tracking website ie, http://royalmail.com/tracking/parcel?=18669.


but I am unable to get this link to show in my webpage,
My WebPage is http://proviewmedia.co.uk/track-trace and you can use Post Code ABC DEF with tracking ID 4
As you will see it displays the site but with #and # and the link is not valid!

Any help would be great.

Code At the top of page,

Inserting a Pre-formated text into database using ado.net

$
0
0

please how can i insert a message into the database and display it exactly as the user type it into the multiline textbox i.e if the user add breakline or many space i want it to be inserted into the databse like that and also when databinding it back to the User interface it should appear exactly as it was input into the database. Thanks

I cannot work this out, i am trying to pick between two dates but it will give keep giving an error.

$
0
0

this.deliveryTableAdapter.Fill(this.deliveryItemsDataSet1.Delivery);

            connectionString =WareHouseConnection.connectionString;

            DeliveryItemOleDb =newOleDbConnection(connectionString);

//DateTime dateF = txtStart.Text;

DateTime dateF = DateTime.ParseExact(dateTimePicker1.Text,"dd/MM/yyyy",newCultureInfo("en-GB"));

DateTime dateE = DateTime.ParseExact(dateTimePicker2.Text,"dd/MM/yyyy",newCultureInfo("en-GB"));

            label3.Text = dateF.ToShortDateString();

            label4.Text = dateE.ToShortDateString();

try

            {

                DeliveryItemOleDb.Open();

                dsWV =newDataSet();

//OleDbCommand DelCommand = new OleDbCommand("SELECT ID, Barcode, ProductName, CompanyName, Quantity, Price, DeliveredOn, EXPDate, UserName FROM [Delivery] WHERE DeliveredOn BETWEEN @StartDate AND @FinishDate", DeliveryItemOleDb);

                DelCommand.CommandText ="SELECT ID, Barcode, ProductName, CompanyName, Quantity, Price, DeliveredOn, EXPDate, UserName FROM [Delivery] WHERE DeliveredOn BETWEEN @StartDate AND @FinishDate";

                DelCommand.Parameters.AddWithValue("@#StartDate#", dateTimePicker1.Value.Date.ToShortDateString());

                DelCommand.Parameters.AddWithValue("@#FinishDate#", dateTimePicker2.Value.Date.ToShortDateString());

                daWV.SelectCommand = DelCommand;

                daWV.Fill(dsWV,"Delivery");

                dataGridView.DataSource = dsWV.Tables["Delivery"];

//DeliveryItemOleDb.Open();

//dsWV = new DataSet();

//sqlWV = "SELECT ID, Barcode, ProductName, CompanyName, Quantity, Price, DeliveredOn, EXPDate, UserName FROM [Delivery] WHERE DeliveredOn (Date as datetime) =#" + label3.Text.ToString() + "#";

//daWV = new OleDbDataAdapter(sqlWV, DeliveryItemOleDb);

//daWV.Fill(dsWV,"Delivery");

//numRowsWV = dsWV.Tables["Delivery"].Rows.Count;

            }

catch (Exception err)

            {           

MessageBox.Show("Please Enter Valid Date!!!"+Environment.NewLine+ "A database error has occurred: "+Environment.NewLine+ err.Message);            

//MessageBox.Show("A database error has occurred: " + Environment.NewLine + err.Message);

            }     

finally

            {

                DeliveryItemOleDb.Close();

            }

 

Can anyone help me please, basically im trying to display all the data from one table on a DGV then allow the user to choose between which dates they would like to see the data.

why i no able to update

$
0
0

wht wrong with my code, my id is set static, any wrong?

if (CheckBoxSub1XS.Checked == true )
            {

                
                using (SqlConnection conStrstock1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
                {

                    string sqlupStock1 = "UPDATE ProductStock SET ProductQty=@qty WHERE ProductID=@pid AND ProductColorType=@protType AND ProductSize=@size";

                    using (SqlCommand cmdupstock1 = new SqlCommand(sqlupStock1, conStrstock1))
                    {
                       
                        cmdupstock1.Parameters.AddWithValue("@pid", Id);
                        cmdupstock1.Parameters.AddWithValue("@protType", "Type1");
                        cmdupstock1.Parameters.AddWithValue("@size", " XS");
                        cmdupstock1.Parameters.AddWithValue("@qty", txtSub1XS.Text);
                        conStrstock1.Open();
                        cmdupstock1.ExecuteNonQuery();
                        conStrstock1.Close();
                        conStrstock1.Dispose();
                        cmdupstock1.Dispose();
                    }
                }
            }

sloce

$
0
0

why in this case i cant use has row keyword? i want to search at bright table and do the if else statement.

using (SqlConnection conStrstock8 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
                {
                    string sqlupStockselect8 = "Select ProductID,ProductColorType,ProductSize WHERE ProductID=@pid AND ProductColorType=@protType AND ProductSize=@size";
                    using (SqlCommand cmdupstock8 = new SqlCommand(sqlupStockselect8, conStrstock8))
                    {
                        cmdupstock8.Parameters.AddWithValue("@pid", Id);
                        cmdupstock8.Parameters.AddWithValue("@protType", "Type8");
                        cmdupstock8.Parameters.AddWithValue("@size", " XS");
                        SqlDataReader myReader = cmdupstock8.ExecuteReader();
                        while (myReader.HasRows())
                        {

                        }
                    }


Update and Insert Problem

$
0
0

It able to update to the database but it pop up error message like this "Violation of PRIMARY KEY constraint 'PK_ProductStock_1'. Cannot insert duplicate key in object 'dbo.ProductStock.' The statement has been terminated."

Your help will be appreciated

Thx you

if (CheckBoxSub8XS.Checked == true && txtSub8XS.Text != "")
            {
                using (SqlConnection conStrstock8 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
                {

                    string sqlupStock8 = "UPDATE ProductStock SET ProductQty=@qty1 WHERE ProductID=@pid AND ProductColorType=@protType AND ProductSize=@size";

                    using (SqlCommand cmdupstock8 = new SqlCommand(sqlupStock8, conStrstock8))
                    {
                        cmdupstock8.Parameters.AddWithValue("@size", " XS");
                        cmdupstock8.Parameters.AddWithValue("@qty1", txtSub8XS.Text);
                        cmdupstock8.Parameters.AddWithValue("@protType", "Type8");
                        cmdupstock8.Parameters.AddWithValue("@pid", Id);

                        conStrstock8.Open();
                        cmdupstock8.ExecuteNonQuery();
                        conStrstock8.Close();

                    }
                }
         }

if (CheckBoxSub8XS.Checked == true)
            {
                using (SqlConnection conINstock8 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
                {

                    string sqlINStock8 = "INSERT INTO ProductStock(ProductID,ProductColorType,ProductSize,ProductQty,ProductSizeEntre,ProductSizeQty) VALUES(@pid,@protType,@size,@qty,@sizeEnt,@sizeQty)";

                    using (SqlCommand cmdINstock8 = new SqlCommand(sqlINStock8, conINstock8))
                    {
                        cmdINstock8.Parameters.AddWithValue("@pid", Id);
                        cmdINstock8.Parameters.AddWithValue("@protType", "Type8");
                        cmdINstock8.Parameters.AddWithValue("@size", " XS");
                        cmdINstock8.Parameters.AddWithValue("@qty", txtSub8XS.Text);
                        cmdINstock8.Parameters.AddWithValue("@sizeEnt", " XS");
                        cmdINstock8.Parameters.AddWithValue("@sizeQty", txtSub8XS.Text);

                        conINstock8.Open();
                        cmdINstock8.ExecuteNonQuery();
                        conINstock8.Close();

                    }
                }
            }

unable to update & insert

$
0
0

Unable to update & insert the checkbox that i select.

This method I use isit correct?or had any method that more suitable?

if (CheckBoxSub8XS.Checked == true && txtSub8XS.Text != "")
            {
                using (SqlConnection conStrstock8 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
                {
                    string sqlupStockselect8 = "Select * FROM ProductStock WHERE ProductID=@pid AND ProductColorType=@protType AND ProductSize=@size";

                    using (SqlCommand cmdupstock8 = new SqlCommand(sqlupStockselect8, conStrstock8))
                    {
                        cmdupstock8.Parameters.AddWithValue("@pid", Id);
                        cmdupstock8.Parameters.AddWithValue("@protType", "Type8");
                        cmdupstock8.Parameters.AddWithValue("@size", " XS");

                        conStrstock8.Open();
                        SqlDataReader myReader = cmdupstock8.ExecuteReader();
                        
                        while (myReader.Read())
                        {
                            if (myReader.HasRows)
                            {
                                using (SqlConnection conStrstock81 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
                                {

                                    string sqlupStock81 = "UPDATE ProductStock SET ProductQty=@qty1 WHERE ProductID=@pid AND ProductColorType=@protType AND ProductSize=@size";

                                    using (SqlCommand cmdupstock81 = new SqlCommand(sqlupStock81, conStrstock81))
                                    {
                                        cmdupstock81.Parameters.AddWithValue("@size", " XS");
                                        cmdupstock81.Parameters.AddWithValue("@qty1", txtSub8S.Text);
                                        cmdupstock81.Parameters.AddWithValue("@protType", "Type8");
                                        cmdupstock81.Parameters.AddWithValue("@pid", Id);

                                        conStrstock81.Open();
                                        cmdupstock81.ExecuteNonQuery();
                                        conStrstock81.Close();

                                    }
                                }
                            }
                            else
                            {
                                using (SqlConnection conINstock8 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
                                {

                                    string sqlINStock8 = "INSERT INTO ProductStock(ProductID,ProductColorType,ProductSize,ProductQty,ProductSizeEntre,ProductSizeQty) VALUES(@pid,@protType,@size,@qty,@sizeEnt,@sizeQty)";

                                    using (SqlCommand cmdINstock8 = new SqlCommand(sqlINStock8, conINstock8))
                                    {
                                        cmdINstock8.Parameters.AddWithValue("@pid", Id);
                                        cmdINstock8.Parameters.AddWithValue("@protType", "Type8");
                                        cmdINstock8.Parameters.AddWithValue("@size", " XS");
                                        cmdINstock8.Parameters.AddWithValue("@qty", txtSub8XS.Text);
                                        cmdINstock8.Parameters.AddWithValue("@sizeEnt", " XS");
                                        cmdINstock8.Parameters.AddWithValue("@sizeQty", txtSub8XS.Text);

                                        conINstock8.Open();
                                        cmdINstock8.ExecuteNonQuery();
                                        conINstock8.Close();

                                    }
                                }
                            }
                        }
                        conStrstock8.Close();
                    }
                }
            }

database delete help on check box list

$
0
0

why i only allow to delete the a item per time if i multiple check the checkbox? how to multiple delete

<div class="productRemove"><asp:CheckBoxList ID="cblprodRemove" runat="server"><asp:ListItem Value="Type1" Enabled="false">Remove Product Color Type 1</asp:ListItem><asp:ListItem Value="Type2">Remove Product Color Type 2</asp:ListItem><asp:ListItem Value="Type3">Remove Product Color Type 3</asp:ListItem><asp:ListItem Value="Type4">Remove Product Color Type 4</asp:ListItem><asp:ListItem Value="Type5">Remove Product Color Type 5</asp:ListItem><asp:ListItem Value="Type6">Remove Product Color Type 6</asp:ListItem><asp:ListItem Value="Type7">Remove Product Color Type 7</asp:ListItem><asp:ListItem Value="Type8">Remove Product Color Type 8</asp:ListItem></asp:CheckBoxList></div>
  if (cblprodRemove.SelectedItem != null)
            {
                using (SqlConnection conDelColType = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
                {

                    string sqlDelColType = "DELETE FROM ProductStock WHERE ProductID = @pid AND ProductColorType = @protType; DELETE FROM ProductImage WHERE ProductID = @pid AND ProductColorType = @protType;";

                    using (SqlCommand cmdDelColType = new SqlCommand(sqlDelColType, conDelColType))
                    {
                        cmdDelColType.Parameters.AddWithValue("@pid", Id);
                        cmdDelColType.Parameters.AddWithValue("@protType", cblprodRemove.SelectedValue);

                        conDelColType.Open();
                        cmdDelColType.ExecuteNonQuery();
                        conDelColType.Close();
                    }
                }
            }



Gregorian Calendar vs. Subscriber Calendar week calculations

$
0
0

I have a database with weeks represented as yyyyww (201323), I need to extract the information for the previous 13 weeks, so far so good but the difficulty is that our calendar is different from the Gregorian one, as the year starts at the end of June e.g. 2013/14 Week 1 is from Friday, 28th June 2013 to Thursday, 4th July 2013, so as you can gather not only the week numbers will not correspond to the standard ISO the week also do not start and end on the normal Sun-Sat or Mon-Sun.

Is there anyone which come across to a similar issue and if so how can it be resolved as I do not have any idea, currently I do have a WHERE statement [code] WHERE (((Tbl_Telephony_All.Week)= (SELECT Max(Tbl_Telephony_All.Week) AS [WeekNo] FROM Tbl_Telephony_All))) [\code] which would extract the information for the MAX ‘week’, however as I need to append the data for a 13 week period into another table I am a bit stock.

 

Any help is very much appreciated.

I believe this is the wrong forun so I re post this at http://answers.microsoft.com/en-us/office/forum/office_2010-access/gregorian-calendar-vs-subscriber-calendar-week/ac20dff2-6e13-45eb-bc9a-99015223120e?tm=1386844945291

Problem Inserting new data on Database

$
0
0

Hey there!

I have an ASP.Net webpage which uses a Microsoft Access database file (MDB). However, I'm having troubles in inserting new data on the MDB file. Here's the code for registering a new user:

Dim MySQL As String = "Insert Into Users(User,Password) VALUES(@user,@password)"

Dim myConn As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=e:\home\bellsistemas\Dados\Test.mdb;Persist Security Info=False")

myConn.Open()
Dim Cmd As New OleDbCommand(MySQL, myConn)
Cmd.Parameters.Add(New OleDbParameter("@user", TextLogin2.Text))
Cmd.Parameters.Add(New OleDbParameter("@password, TextSenha2.Text))

Cmd.ExecuteNonQuery()

myConn.Close()

Then I get an error message: 

Operation must use an updateable query.

It's a strange thing, because I can edit or delete data when I have a Gridview showing the data from the respective database but I can't insert new data.

Did I forgot something?

Thanks for those who can help me!

Proper way to close a connection?

$
0
0

Hi, I'm hoping you guys can tell me if I'm doing this right - especially, if I am closing the connection properly.  Thanks in advance.

Dim sql, dbcomm, dbread, DCatA, DCatB
        Dim connectionString As String
        Dim dbconn As OleDbConnection
        connectionString = ConfigurationManager.ConnectionStrings("MyConnectionString").ToString
        dbconn = New OleDbConnection(connectionString)
        dbconn.Open()
        sql = "SELECT * FROM tbl_HomePageHighlights WHERE Website LIKE 'msphds.org' AND ExpireDate > Now"
        dbcomm = New OleDbCommand(sql, dbconn)
        dbread = dbcomm.ExecuteReader()
        If dbread.HasRows Then
            While dbread.Read()
                'do stuff
            End While
        End If
        dbread.close()
        dbconn.Close()

S.O.S -Unable to update the data

$
0
0

Here is my code:I can't found the error...Need your help!!Thankssss

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{

hidmatrixNo.Value = Request.QueryString["matrixNo"];
hidAct.Value = Request.QueryString["act"];
BindStudent();

if (hidAct.Value.ToString() == "View")
{
name.Visible = false;
prmAddress.Visible = false;
faculty.Visible = false;
programme.Visible = false;
batch.Visible = false;
research.Visible = false;
regDate.Visible = false;
btnClear.Visible = true;
lblBlock1.Visible = false;
btnUpdate.Visible = true;
btnDelete.Visible = false;
}

if (hidAct.Value.ToString() == "Delete")
{
name.Visible = false;
prmAddress.Visible = false;
faculty.Visible = false;
programme.Visible = false;
batch.Visible = false;
research.Visible = false;
regDate.Visible = false;
btnClear.Visible = false;
lblBlock1.Visible = true;
btnUpdate.Visible = false;
btnDelete.Visible = true;
}

}
}

protected void btnUpdate_Click(object sender, EventArgs e)
{
string connStr = ConfigurationSettings.AppSettings["connstring"].ToString();
MySqlConnection myConn = new MySqlConnection(connStr);
myConn.Open();
string strSqlComm = "", strScript;
int row_Index;

try
{
if ((txtSupplierName.Text.Trim().Length <= 0) || (txtAddr1.Text.Trim().Length <= 0) ||
(txtPost.Text.Trim().Length <= 0) || (txtState.Text.Trim().Length <= 0) ||
(txtCountry.Text.Trim().Length <= 0) || (txtPhone.Text.Trim().Length <= 0) ||
(txtEmail.Text.Trim().Length <= 0))
{
strScript = "alert('Please enter all details.');";
ScriptManager.RegisterStartupScript(this, typeof(string), "open", strScript, true);
}
else
{
strSqlComm = "UPDATE lsSupplier SET supplierName = '" + SafeDBString(txtSupplierName.Text) + "', address1 = '" +
SafeDBString(txtAddr1.Text) + "', address2 = '" + SafeDBString(txtAddr2.Text) + "', address3 = '" +
SafeDBString(txtAddr3.Text) + "', postCode = '" + SafeDBString(txtPost.Text) + "', state = '" +
SafeDBString(txtState.Text) + "', country = '" + SafeDBString(txtCountry.Text) + "', phone = '" +
SafeDBString(txtPhone.Text) + "', email = '" + SafeDBString(txtEmail.Text) + "' WHERE supplierId = '" +
hidSupplierId.Value.ToString() + "' ";

MySqlCommand sqlComm1 = new MySqlCommand(strSqlComm, myConn);
row_Index = sqlComm1.ExecuteNonQuery();

if (row_Index > 0)
{
strScript = "alert('Successfully updated.'); window.location='SupplierList.aspx';";
ScriptManager.RegisterStartupScript(this, typeof(string), "open", strScript, true);
}
}
}
catch (Exception)
{
throw;
}
finally
{
myConn.Close();
}
}

#region Private Method


private void BindStudent()
{
string connStr = ConfigurationManager.AppSettings["connstring"].ToString();
MySqlConnection myConn = new MySqlConnection(connStr);
myConn.Open();
string strSqlComm;

try
{
strSqlComm = "SELECT * FROM student WHERE matrixNo = '" + hidmatrixNo.Value.ToString() + "' ";

MySqlCommand sqlComm = new MySqlCommand(strSqlComm, myConn);

MySqlDataAdapter sda = new MySqlDataAdapter(sqlComm);
DataSet dsStudent = new DataSet();
sda.Fill(dsStudent);

if (dsStudent.Tables[0].Rows.Count > 0)
{
matrixNo.Text = dsStudent.Tables[0].Rows[0]["matrixNo"].ToString();
txtName.Text = dsStudent.Tables[0].Rows[0]["name"].ToString();
name.Text = dsStudent.Tables[0].Rows[0]["name"].ToString();
txtAddr1.Text = dsStudent.Tables[0].Rows[0]["prmAddress"].ToString();
prmAddress.Text = dsStudent.Tables[0].Rows[0]["prmAddress"].ToString();
txtFac.Text = dsStudent.Tables[0].Rows[0]["faculty"].ToString();
faculty.Text = dsStudent.Tables[0].Rows[0]["faculty"].ToString();
txtProg.Text = dsStudent.Tables[0].Rows[0]["programme"].ToString();
programme.Text = dsStudent.Tables[0].Rows[0]["programme"].ToString();
txtbatch.Text = dsStudent.Tables[0].Rows[0]["batch"].ToString();
batch.Text = dsStudent.Tables[0].Rows[0]["batch"].ToString();
txtTitle.Text = dsStudent.Tables[0].Rows[0]["research"].ToString();
research.Text = dsStudent.Tables[0].Rows[0]["research"].ToString();
txtDate.Text = dsStudent.Tables[0].Rows[0]["regDate"].ToString();
regDate.Text = dsStudent.Tables[0].Rows[0]["regDate"].ToString();
}
}
catch (Exception)
{
throw;
}
finally
{
myConn.Close();
}

#endregion
}


Oracle 8 and ADO

$
0
0

Hi all. I'm trying to create a web application with MVC (but with web forms there's same error) but every time I open databse connection, I receive this error:

ORA-06413: Connection not open.

I use Visual Studio 2012 Ultimate on Windows 7 64bit.

This is a bit of code:

OleDbConnection conn = new OleDbConnection(_ConnStr);
OleDbCommand com = null;
OleDbDataReader reader = null;

try {
    string sQuery = "SELECT * FROM MYTABLE WHERE CODE = :Code";
    com = new OleDbCommand(sQuery, conn);
    com.Parameters.Add(":Code", OleDbType.VarChar).Value = myCode;

    conn.Open(); //exception

If I use same code in a Windwos Console project, it execute without problem. I found many solution on web, but nothing change:

http://blogs.msdn.com/b/jason_howell/archive/2010/09/02/oracle-error-when-connecting-from-powerpivot-for-excel-2010-connection-not-open.aspx

http://www.networksteve.com/enterprise/topic.php/On_Windows_7_%2864-bit%29:_How_to_use_MS_Access_2007_to_link_to_Orac/?TopicId=24924&Posts=0

Any solution?

database cannot be made

$
0
0

whenever i tried to make a new database in visual basic 2008 i got an error message:

"A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfces, error:26 - Error Locating Server/Instance Specified)"

please tell me how this error be removed

asp.net .vb UPDATE ms access database not working

$
0
0

Hi all,

I am unable to do an update data to my ms access database table. After i run my .aspx, i check the database table but still data not updated.

The SELECT SQL statement works perfectly fine and I am able to set the counter to 1

but I can't do an UPDATE. I try INSERT statement also cannot work.

I try to use breakpoint but still cannot figure out whats wrong. My codes seems fine.

What has actually gone wrong? My Code? Need to configure some setting on the ms access DB for update statement?

Please see below 3 screenshot. Please advice!

 

Opening a mdb with C# and extracting forms, tables,etc

$
0
0

I am on a project to convert a large number of mdb applications as well as some later version applications, the 2010 and 2013 versions to dot net.  Can someone point me at documentation on how to read (these are not password protected or anything like that) the .mdbs and extract the information from them.  Thanks

 

DonnieS

Connection to an Access Database not working

$
0
0

I am working with this code which I have based off another working code that uses SQL Server.  I cannot get this same situation to work with an Access database.  The idea of the code is to check if the work order input into the texbox is unique before it is submitted to the db.

I get the error, "Keyword not supported: Provider".  This leads me to believe that the SqlConnection doesn't work well with an Access database.  Is that true?  If so, what should I use instead?  Or do I just need to alter my connection string.  This connection string works with other sqldatasources in other files in the same website, so I don't really understand why it doesn't work in the code behind.

Html Source:

<%@ Page Title="" Language="VB" MasterPageFile="~/MasterPages/Frontend.master" AutoEventWireup="false" CodeFile="testWO.aspx.vb" Inherits="testWO" %><asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"></asp:Content><asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"><asp:UpdatePanel ID="UpdatePanel1" runat="server"><ContentTemplate><asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True"></asp:TextBox><asp:Label ID="Label1" runat="server"></asp:Label><br /><br /><asp:Label ID="Label2" runat="server" Text="Label"></asp:Label><asp:GridView ID="GridView1" runat="server"></asp:GridView></ContentTemplate></asp:UpdatePanel></asp:Content><asp:Content ID="Content3" ContentPlaceHolderID="foot" Runat="Server"></asp:Content>



VB.Net Source - Code Behind

Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Data
Imports System.Data.Odbc

Partial Class testWO
    Inherits System.Web.UI.Page

    Protected Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged

        If TextBox1.Text <> String.Empty Then
            Dim connection As String = ConfigurationManager.ConnectionStrings("fpimsConnectionString").ConnectionString
            'this is the connection string  -->  "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\fpims.mdb"

            Label2.Text = connection


            Dim selectcommand As String = "SELECT COUNT(*) FROM WorkOrders WHERE WorkOrder = @WorkOrder"
            Dim con As New SqlConnection(connection)  'this is where it errors
Dim cmd As New SqlCommand(selectcommand, con) Dim workOrder As New SqlParameter("@WorkOrder", DbType.String) workOrder.Value = TextBox1.Text.Trim().ToString() cmd.Parameters.Add(workOrder) con.Open() Dim result As Integer = DirectCast(cmd.ExecuteScalar(), Int32) con.Close() If result >= 1 Then Label1.Text = "Work Order not available" Label1.ForeColor = System.Drawing.Color.Red Else Label1.Text = "Available" Label1.ForeColor = System.Drawing.Color.Green End If End If End Sub End Class

Viewing all 518 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>