C# .NET - Run time Error:ArgumentException was unhandled by user code.

Asked By Elvin
26-Sep-11 09:01 AM
Code is below and yellow background on code section indicates where the error occurred.
I am doing a school project . Please help:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Data.SqlTypes;

namespace zephyrAir2
{
    public partial class logIn : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            //Declaring variables for login controls and setting each to nothing
            string username = null;
            string pwd = null;
            string pName = null;

            username = Login1.UserName;
            pwd = Login1.Password;
            pName = "";

           //Declaring connection string
            string strConn = null;
           // strConn = WebConfigurationManager.ConnectionStrings("ConnectionASPX").ConnectionString;

            //* Setting a database path to the database
            strConn = Server.MapPath("Data Source = tblsZephyrAir.mdb");

            // * Declare and instantiate the SqlConnection
            // * The SqlConnection object instantiated below uses a constructor with a single argument of type string.
            // * This argument is called a connection string.  
            SqlConnection Conn = new SqlConnection(strConn);

            //Opening connection
            Conn.Open();

            // *Setting Username as nothing and database query to search for the username and password
            string sqlUsername = null;
            sqlUsername = "SELECT Username,Password FROM UserAccounts ";
            sqlUsername += " WHERE (Username = @Username";
            sqlUsername += " AND Password = @Password)";


            SqlCommand com = new SqlCommand(sqlUsername, Conn);
            com.Parameters.AddWithValue("@Username", username);
            com.Parameters.AddWithValue("@Password", pwd);


            string Currentname = null;
            Currentname = Convert.ToString(com.ExecuteScalar());

            if (!string.IsNullOrEmpty(Currentname))
            {
                Session["UserAuthentication"] = username;

                Response.Redirect("ZephyrIndex.aspx");
            }
            else
            {
                Session["UserAuthentication"] = "";
            }
           

        }       
    }  
   }

I am trying to have the user log in using a tblsZephyrAir.mdb database I created and have them redirected to the ZephyrIndex.aspx page which is the Home Page in other words. It says" ArgumentException was unhandled by user code. "
It also says " Keyword not supported: 'c:\users\userpcone\downloads\zephyrair2\zephyrair2\data source'."
       

  Sakshi a replied to Elvin
26-Sep-11 09:58 AM

sqlconnection is used for sql server db only, use the following instead,


using System.Data.Odbc;

OdbcConnection conn = new OdbcConnection();
conn.ConnectionString =
  "Driver={Microsoft Access Driver (*.mdb)};" +
  "Dbq=c:\myPath\myDb.mdb;" +
  "Uid=Admin;Pwd=;";
conn.Open();


  Suchit shah replied to Elvin
26-Sep-11 10:45 AM
1st 
check ur web.config file where u have been used "ConnectionASPX" as a connection string... verify it is correct or not
2nd 
if u r using MDB access as a database in back hand then u can not use sqlconnection, sqlcommand,sqladapater........ instead of this u required 2 use oldbbconnection, oledbcommand,oledbdataadapter


Hope this much resolved ur issue
  Suchit shah replied to Elvin
26-Sep-11 10:59 AM
use it on this way

<%@ Page Language="http://www.developerfusion.com/t/csharp/" Debug="true" %>
<%@ import Namespace="CrystalDecisions.CrystalReports.Engine" %>
<%@ import Namespace="CrystalDecisions.Shared" %>
<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.IO" %>
<%@ import Namespace="System.Xml" %>
<%@ import Namespace="System.Text" %>
<script runat="server">
    public void Page_Load(Object sender, EventArgs E) {
        //*** INSTRUCTIONS:
        //define action for this program
        //1. set action to "CreateSchemaFile"
        //2. run program which creates your .xsd schema file
        //3. create crystal report based on that file
        //4. then set action permanently to "CreatePdf"
        //the command
        string action = "CreatePdf";
        //variables
        string tableName = "fin";
        string rptFile = "fin.rpt";
        string xsdFile = "fin.xml";
        string pdfFile = "fin.pdf";
        //either create the schema (first time only) or the pdf file
        if(action.ToUpper() == "CREATESCHEMAFILE") {
            DataTable dt = new DataTable();
            dt = DummyTable();
            DataSet ds = new DataSet();
            ds.Tables.Add(dt);
            CreateSchemaFile(xsdFile,ds);
            Response.Write("Your schema file has been created:<br/><br/> <b>" + Server.MapPath(xsdFile) + "</b><br/><br/>");
            Response.Write("Use it to create your Crystal Reports report file named:<br/><br/> <b>" + Server.MapPath(pdfFile) + "</b>");
        } else {
            //create the report document
            ReportDocument doc = new ReportDocument();
            string fileName = Server.MapPath(rptFile);
            doc.Load(fileName);
            DataTable dt = DummyTable();
            dt.TableName = tableName;
            DataSet ds = new DataSet();
            dt.TableName    = "Table";
            ds.Tables.Add(dt);
            doc.SetDataSource(ds);
            ExportOptions exportOpts = doc.ExportOptions;
            exportOpts.ExportFormatType = ExportFormatType.PortableDocFormat;
            exportOpts.ExportDestinationType = ExportDestinationType.DiskFile;
            exportOpts.DestinationOptions = new DiskFileDestinationOptions();
            // Set the disk file options.
            DiskFileDestinationOptions diskOpts = new DiskFileDestinationOptions();
            ( ( DiskFileDestinationOptions )doc.ExportOptions.DestinationOptions ).DiskFileName = Server.MapPath("fin.pdf");
            doc.Export();
            Response.Write(dt.Rows.Count);
            Response.Write("<a href=\"" + pdfFile + "\">" + pdfFile + "</a>");
        }

    }
    private void CreateSchemaFile(string fileName, DataSet ds) {
        string absoluteFileName = HttpContext.Current.Server.MapPath(fileName);
        FileStream myFileStream = new FileStream (absoluteFileName, FileMode.Create);
        XmlTextWriter myXmlWriter = new XmlTextWriter(myFileStream, Encoding.Unicode);
        ds.WriteXml( myXmlWriter,XmlWriteMode.WriteSchema );
        myXmlWriter.Close();
    }
    private DataTable GetTheData() {
        //get datatable
        DataTable dt = qs.GetDataTable("SELECT * FROM fin");
        DataTable d2 = dt.Copy();
        return d2;
    }
    private DataTable DummyTable()    {
        //create table
        DataTable dt = new DataTable("Employees");
        dt.Columns.Add("id",Type.GetType("System.Int32"));
        dt.Columns.Add("FirstName",Type.GetType("System.String"));
        dt.Columns.Add("LastName",Type.GetType("System.String"));
        dt.Columns.Add("HireDate",Type.GetType("System.DateTime"));
        //fill rows
        DataRow dr;
        for(int x=1;x<=10;x++) {
            dr = dt.NewRow();
            dr["id"] = x;
            dr["FirstName"] = "Joe" + x;
            dr["LastName"] = "Smith" + x;
            dr["HireDate"] = DateTime.Now;
            dt.Rows.Add(dr);
        }
        return dt;
    }
</script>
<!--#include file="qs.aspx" -->
  Anoop S replied to Elvin
26-Sep-11 03:31 PM
tblsZephyrAir.mdb -> means your database is access so in order use ms access database you should use OleDb(Object Linking and Embedding, Database, sometimes written as OLEDB or OLE-DB)
  Elvin replied to Anoop S
27-Sep-11 07:20 AM
Well, I am actually using a database I created using ASP.NET by going to Add Item in the Solution Explorer Project > Then selecting SQL Server Database and I named it tblsZephyrAir where it got all the tables needed for the project such as UserAccounts, AffiliateCompany, Orders, OrderDetails, LineItems, Customers,  plus many more. The extension is .mdb  and I did not use MS Access for it since it is a .accdb extension. 
Create New Account
help
Failed to connect to SQL Server SQL Server Greetings, Good day. I am having a SQL Server connectivity issue as below: - web.config - -- -- -- -- - Source = server;Initial Catalog = UserDB;User ID = sa_userdb;Password = passWord;" providerName = "System.Data.SqlClient" / > d: \ Project \ Web sec = (ConfigurationManager.GetSection("SBDataProviders")) as SBDataProvidersSection; string connectionStringName = sec.CatalogProviders[sec.CatalogProviderName].Parameters["connectionStringName"]; return WebConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString; } Server Error in ' / BW' Application. - -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - Object reference not set to an instance
SQL Connection Issue SQL Server Greetings, Good day. I am having a SQL Server connectivity issue as below: - web.config - -- -- -- -- - Source = server;Initial Catalog = UserDB;User ID = sa_userdb;Password = passWord;" providerName = "System.Data.SqlClient" / > d: \ Project \ Web sec = (ConfigurationManager.GetSection("SBDataProviders")) as SBDataProvidersSection; string connectionStringName = sec.CatalogProviders[sec.CatalogProviderName].Parameters["connectionStringName"]; return WebConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString; } Server Error in ' / BW' Application. - -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - Object reference not set to an instance of an object. Description
Error:A network-related or instance-specific error occurred The full error during Run Time: Server Error in ' / ' Application. 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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) Description: An unhandled exception occurred during the execution of the current web request. Please review
SQL server connection string Hello every one . . . . . can you give me the syntax of the connection string from Asp.net c# to SQL server data base . . . i attend to access SQL data base from Asp.net C# application With the connection In Web.config and then sa; " providerName = " System.Data.SqlClient " / > Check out this link as well; http: / / www.connectionstrings.com / sql-server-2005 Show here good article http: / / www.csharp-station.com / Tutorials / AdoDotNet / Lesson02.aspx http: / / www.aspnettutorials.com / tutorials / database / connect-sql-datasource-csharp.aspx Thank you sir. . . but it gives me an error it said that
How to insert values into sql server using jquery hi frds How to insert values into sql server using jquery Hi Client Side scripting is there to do miracles in the Client Side only but not on the Server Side.We can't do this using jQuery or Javascript. Follow this example- Record in Script.Services. ScriptService ] public class MultipleUpdateWebService : System.Web.Services. WebService { / / getting connection string string conStr = WebConfigurationManager .ConnectionStrings[ "SampleTestDBConnectionString1" ].ConnectionString; int rowsInserted = 0; [ WebMethod ] public string ReceiveUpdatesWebservice( string name, string email, string phone, string address) { / / Creating Sql Connection using ( SqlConnection conn = new SqlConnection (conStr)) { / / Creating insert statement string sql = string .Format( @"INSERT INTO [SampleTestDB].[dbo].[SampleInfoTable] ([Name] , [Email] , [Phone] , [Address]) VALUES ('{0}' , '{1}' , '{2