Elmo_loves_you 20 Junior Poster in Training

Ooops I mean a ComboBox

I must be being thick.
listBox1.SelectedItem

Yes, I have tried that. But for some reason its not working. I am probably doing something in the wrong order.

private void cbo_companyName_SelectedIndexChanged(object sender, EventArgs e)
        {
            getCompanyName(); //populates the Cbox with the data - it works
            getCompanyID();  //returns the uniqueID for the selected item - doesnt work
        }

Above shows the method calls I have in the SelectedIndexChanged event

public void getCompanyName() //Method to return list of company names and add to listbox
        {
            //Clear the listbox
            cbo_companyName.Items.Clear();
            
            //Create SQL command, declare SPROC and connection to database
            myCommand = new SqlCommand("get_CompanyName", myConnection);
            myCommand.CommandType = CommandType.StoredProcedure;
            
            //Open database connection
            myConnection.Open();

            //Execute myCommand into the reader and close the connection
            myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            
            while (myReader.Read())//== true)
            {
                //Loop through the reader appending each element to the list                
                cbo_companyName.Items.Add(myReader.GetString(1));
            }
            //Close and dispose of open properties
            myReader.Close();
            myCommand.Dispose();
        }

Now the following method is the one that returns the Unique ID, I tested it using two text boxes, one where I ran the program and manually entered a Name, then clicked a button and the ID was displayed in the second textbox.

So, I just need to force it to take the selected value and pass it into the stored procedure

public void getCompanyID()
        {
            //Create SQL command, declare SPROC and connection to database
            myCommand = new SqlCommand("findCompanyid", myConnection);
            myCommand.CommandType = CommandType.StoredProcedure;

            //Open database connection
            myConnection.Open();

            myCommand.Parameters.Add(new SqlParameter("@companyName", SqlDbType.VarChar, 50, "CompanyName"));
            //myCommand.Parameters["@companyName"].Value = cbo_companyName.SelectedText; …
Elmo_loves_you 20 Junior Poster in Training

oooh yea lol

but still ... surely there is a simple property of the comboBox control to force the DATA to be passed to a VARIABLE (which could be used for further manipulation)

I have used a dropdownlist control in ASP.NET before where I was able to say

myCommand.Parameters["@companyName"].Value = ddl_companyName.SelectedValue;

and that value was passed into the stored procedure and executed correctly.

I dont know what you mean by dictionary ... Ive tried googling but im still none the wiser.

Elmo_loves_you 20 Junior Poster in Training

Hi

I have a stored procedure that returns the unique ID for a particular Name/string passed in.

On my windows form I have a ListBox control filled with a list of names (returned from another stored procedure)

I want to be able to let the user click the list box and select a name ... then once they have selected the name that value would be passed into my new stored procedure to return the unique ID which i then want to display in a hidden textbox for further usage.

Can anyone point me in the right direction with this.

The following uncommented lines of code illustrate what I am trying to do to get the contents of the users selection

//myCommand.Parameters["@companyName"].Value = cbo_companyName.SelectedText;
//myCommand.Parameters["@companyName"].Value = cbo_companyName.SelectedItem;

Many Thanks :)

Elmo

Elmo_loves_you 20 Junior Poster in Training

Hi

Would it be because while you are testing it in the IDE the database connection string is pointing to the mdb database file within your bin/debug folder explicitly rather than replacing the file path with |datadirectory| so that it would be relative to wherever you have the database stored!

just a guess :)

Elmo_loves_you 20 Junior Poster in Training

Never mind, Sorted :)

Hi

I have a tabbed control. Tab1 is for adding new customer details and Tab2 is for searching for existing customers (from a comboBox) and then adding additional information for that customer.

How can I make the results of a stored procedure be automatically displayed in the comboBox(DropDownList) as soon as the user clicks on that tab?

Thanks

Elmo

Elmo_loves_you 20 Junior Poster in Training

Hi

I have a tabbed control. Tab1 is for adding new customer details and Tab2 is for searching for existing customers (from a comboBox) and then adding additional information for that customer.

How can I make the results of a stored procedure be automatically displayed in the comboBox(DropDownList) as soon as the user clicks on that tab?

Thanks

Elmo

Elmo_loves_you 20 Junior Poster in Training

Hi,

Sorry for posting again but this is really starting to annoy me now.

I have created a form with textboxes for user input!

Stored procedures to add the parameter data to the table (which executes correctly and adds new data to the table)

Then I wrote this code ... I have changed it to match the code that I used for my university ASP.NET project which added new data to the database successfully. I was able to perform all CRUD tasks.

But for some reason I cant get the data to add to the table, stepping through the code indicates that the connection is Open!! So I really cant understand whats going wrong.

myConnection is just an SqlConnection myConnection = new SqlConnection("sjkfskjfhskjhf"); declared at top of code

//Declare myCommand properties
            myCommand = new SqlCommand("CreateCustomer", myConnection);
            myCommand.CommandType = CommandType.StoredProcedure;
            
            //Open connection to the database
            myConnection.Open();

            myCommand.Parameters.Add(new SqlParameter("@companyName", SqlDbType.VarChar, 50, "CompanyName"));
            myCommand.Parameters["@companyName"].Value = txt_CompanyName.Text;

            myCommand.Parameters.Add(new SqlParameter("@forename", SqlDbType.VarChar, 50, "ContactForename"));
            myCommand.Parameters["@forename"].Value = txt_ContactForename.Text;

            myCommand.Parameters.Add(new SqlParameter("@surname", SqlDbType.VarChar, 50, "ContactSurname"));
            myCommand.Parameters["@surname"].Value = txt_ContactSurname.Text;

            myCommand.Parameters.Add(new SqlParameter("@phoneNo", SqlDbType.NVarChar, 50, "PhoneNo"));
            myCommand.Parameters["@phoneNo"].Value = txt_PhoneNo.Text;

            myCommand.Parameters.Add(new SqlParameter("@mobileNo", SqlDbType.NVarChar, 50, "MobileNo"));
            myCommand.Parameters["@mobileNo"].Value = txt_MobileNo.Text;

            myCommand.Parameters.Add(new SqlParameter("@altNo", SqlDbType.NVarChar, 50, "AlternativeNo"));
            myCommand.Parameters["@altNo"].Value = txt_AlternativeNo.Text;

            myCommand.ExecuteNonQuery();
            myCommand.Dispose();
            myConnection.Close();

            lbl_SuccessfulMessage.Text = "Success";

Please help lol :(

Elmo_loves_you 20 Junior Poster in Training
// Note: GetSqlConnection simply returns my connection string.
public static void ExecuteNonQueryStoredProcedure(string ProcedureName, params SqlParameter[] values)
        {
            SqlConnection conn = GetSqlConnection();
            SqlCommand cmd = new SqlCommand(ProcedureName, conn);
            cmd.CommandTimeout = 60;
            cmd.CommandType = CommandType.StoredProcedure;
            if (values != null && values.Length > 0)
                cmd.Parameters.AddRange(values);
            try
            {
                conn.Open();
                cmd.ExecuteNonQuery();
            }
            finally // NO CATCH ON PURPOSE, want the error to escelate
            {
                conn.Close();
                conn.Dispose();
            }
        }

One last question Jerry. For the highlighted method call above. How did you write that method? I really do have a lot to learn !!

public void GetSqlConnection()
        {
            SqlConnection connection = new SqlConnection("THE LONG WINDED CONN STRING");
            //return connection;
        }

I havent got a static class set up at the moment ... but once I get this working I will be able to play about with it :)

Elmo_loves_you 20 Junior Poster in Training

Thanks very much Jerry, that looks very neat :) I'll give it a go and let you know how I get on

Thanks

Elmo_loves_you 20 Junior Poster in Training

Jerry,

I have a question related to this post!

I am trying to develop a Windows Application interface to an SQL Server database. I have a stored procedure that executes properly and successfully adds to the table in the database.

However the C# code that I have written to pass data to the stored procedure via textboxes on the interface is not working as expected. I am not getting any obvious 'bugs' but the data is still not adding to the table.

I hope you can help me with this issue

public void setCustomerDetails()
        {
            try
            {
                //Open connection to the database
                myConnection.Open();

                //Declare myCommand properties
                myCommand = new SqlCommand("CreateCustomer", myConnection);
                myCommand.CommandType = CommandType.StoredProcedure;

                //Declare and Initialise the stored procedure parameters setting their type and size
                //as they are defined in the table properties!
                param_companyName = new SqlParameter("@companyName", SqlDbType.VarChar, 50);
                param_companyName.Value = txt_CompanyName.Text;

                param_contactForename = new SqlParameter("@forename", SqlDbType.VarChar, 50);
                param_contactForename.Value = txt_ContactForename.Text;

                param_contactSurname = new SqlParameter("@surname", SqlDbType.VarChar, 50);
                param_contactSurname.Value = txt_ContactSurname.Text;

                param_phoneNo = new SqlParameter("@phoneNo", SqlDbType.NVarChar, 50);
                param_phoneNo.Value = txt_PhoneNo.Text;

                param_mobileNo = new SqlParameter("@mobileNo", SqlDbType.NVarChar, 50);
                param_mobileNo.Value = txt_MobileNo.Text;

                param_altNo = new SqlParameter("@altNo", SqlDbType.NVarChar, 50);
                param_altNo.Value = txt_AlternativeNo.Text;

                myCommand.Parameters.Add(param_companyName);
                myCommand.Parameters.Add(param_contactForename);
                myCommand.Parameters.Add(param_contactSurname);
                myCommand.Parameters.Add(param_phoneNo);
                myCommand.Parameters.Add(param_mobileNo);
                myCommand.Parameters.Add(param_altNo);
               
                myCommand.ExecuteNonQuery();

                lbl_SuccessfulMessage.Text = "Success";
            }
            catch (SqlException ex)
            {
                lbl_SuccessfulMessage.Text = ex.Message;
            }
            finally
            {
                //Close database connection
                myConnection.Close();
            }
}

PS. I used this approach when I was working on an ASP.NET project :) and it worked fine

Elmo_loves_you 20 Junior Poster in Training

Hi

I have previously populated a listbox / dropdown list with data from a stored procedure in ASP.NET C# and called the method in the PageLoad so that the list would be available once the page loaded up.

However, now I want to do the same thing except I want to do it for a Windows Application and not a website. So, how can I make the listbox automatically display the results of the sproc?

public void getCompanyName() //Method to return list of company names and add to listbox
        {
            //Clear the listbox
            listBox_CompanyName.Items.Clear();
            //Create SQL command, declare SPROC and connection to database
            myCommand = new SqlCommand("get_CompanyName", myConnection);
            myCommand.CommandType = CommandType.StoredProcedure;
            //Open database connection
            myConnection.Open();

            //Execute myCommand into the reader and close the connection
            myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

            while (myReader.Read())
            {
                //Loop through the reader appending each element to the listbox
                listBox_CompanyName.Items.Add(myReader.GetString(1));
               
            }
            
            myReader.Close();
            myCommand.Dispose();
        }

Has anyone any ideas please? :)

Elmo_loves_you 20 Junior Poster in Training

Perhaps you could guide me on how to use datasets and adapters with stored procedures :)

Elmo_loves_you 20 Junior Poster in Training

what is MyGrid referring to in this code ^^^ ???

Elmo_loves_you 20 Junior Poster in Training

Never mind, got her sorted! :)

just used the textbox.text directly rather than passing it to a string variable

:)

Elmo_loves_you 20 Junior Poster in Training

Hi Everyone,

I know this sounds silly but Ive been so caught up with designing efficient logins that interact with a database that Ive forgotten how to do it the hard coded way.

I have to create a little application that interacts with a database, but it doesnt have to be so complex as its just going to be an "in-house" application if you like.

****** The problem ******

string username, password; //String variable declarations

public void validateLogin()
        {
            //Check if data entered matches correct log in details
            if (input_username == username) // && password == input_password)
                lbl_status.Text = "Test string should display if username is equal";
                //Login successful - display message
                //Set tabbed pane to visible
                //tabControl1.Visible = true;
               
            //Else display unsuccessful message
            //else lbl_status.Text = "Sorry, the details you entered were incorrect.  Try again!";
        }

// Then button click event to call the validateLogin method

Surely my approach to this is right, the aim was to keep it simple lol but I seem to have forgotten the basic algorithm.

Please help

## input_username is a string holding data entered in a textbox.text

Elmo_loves_you 20 Junior Poster in Training

Yes - the connection string is correct... I just typed that in for Brevity.

Stepping through the code indicates that the connection is open when it should be. I am trying to make a windows forms application and have written stored procedures that successfully insert / update the database.

I have used this code before for an ASP.NET website and it worked perfectly (2005) but now I want to use the same method of inserting/updating except that it is for (2008) desktop application

Elmo_loves_you 20 Junior Poster in Training

Hi.

I have previously designed an ASP.NET system that interacted with SQL Server 2005. I now want to design a desktop application using Visual Studio 2008 that interacts with an SQL database. I had planned to use the same sort of coding to implement this new system.

For example - I have stored procedures that successfully add new data to the database tables. Previously I used the following code which works but similar code doesnt work in 2008.

SqlConnection myConnection = new SqlConnection("THE LONG CONNECTION STRING");
SqlDataReader myReader;
SqlCommand myCommand;

public void getCustomerDetails()
{
            //Declare myCommand properties
            myCommand = new SqlCommand("CreateCustomer", myConnection);
            myCommand.CommandType = CommandType.StoredProcedure;
            //Open connection to the database
            myConnection.Open();
            
            //Declare and Initialise the stored procedure parameters
            myCommand.Parameters.Add(new SqlParameter("@companyName", SqlDbType.VarChar, 50, "CompanyName"));
            myCommand.Parameters["@companyName"].Value = txt_CompanyName.Text;

            myCommand.Parameters.Add(new SqlParameter("@forename", SqlDbType.VarChar, 50, "ContactForename"));
            myCommand.Parameters["@forename"].Value = txt_ContactForename.Text;

            myCommand.Parameters.Add(new SqlParameter("@surname", SqlDbType.VarChar, 50, "ContactSurname"));
            myCommand.Parameters["@surname"].Value = txt_ContactSurname.Text;

            myCommand.Parameters.Add(new SqlParameter("@phoneNo", SqlDbType.NVarChar,50,"PhoneNo"));
            myCommand.Parameters["@phoneNo"].Value = txt_PhoneNo.Text;

            myCommand.Parameters.Add(new SqlParameter("@mobileNo", SqlDbType.NVarChar,50,"MobileNo"));
            myCommand.Parameters["@mobileNo"].Value = txt_MobileNo.Text;

            myCommand.Parameters.Add(new SqlParameter("@altNo", SqlDbType.NVarChar, 50, "AlternativeNo"));
            myCommand.Parameters["@altNo"].Value = txt_AlternativeNo.Text;

            //Close and dispose of open properties
            myCommand.ExecuteReader();  //**** ERROR here ******
            myCommand.Dispose();
            myConnection.Close();
}

In debug mode it throws an InvalidOperationException at the line indicated above ****

"ExecuteReader requires an open and available Connection. The connections current state is closed."

Although when I step through the code it states that the connection is open.

Has anyone got any ideas??

Elmo_loves_you 20 Junior Poster in Training

Jerry thank you very much :)

It opens files based on the ID but the original data is not in them. Would this be because they are not decrypted yet? What they show in the file is

d:\enc-outfile-4027820

I must also do some validation that only returns the most recent file making use of the date and time submitted!

Another wee thing too...how can I tell the file to save to the disk only and not open in a document? Because I need to be able get the string value of the path where the file is saved so that it can pass into the decryption method.

Thank you so very much for your help

you're a wee star :)

Elmo_loves_you 20 Junior Poster in Training

have you any ideas?

Elmo_loves_you 20 Junior Poster in Training

Here is the stored procedure code, the parameter for this I want to pass in via the form (hidden textbox) The correct ID is being displayed in this textbox so the correct data should definately be passed into the Sproc. For the decryption process I am trying to create two temporary files on disk which I can then use the filepath (string value) to pass into the decryption code. Its bypassing the while loop completely

ALTER PROCEDURE dbo.getEncryptedAssignments 
--Returns the encrypted assignment and pKey blob files
--based on the ID entered
	(
	@studentID int
	)

AS
--DECLARE @studentID int

SELECT     Assignment, pKey, Filename
FROM         AssignmentSubmissions
WHERE		StudentID = @studentID

	RETURN
public static byte[] ToByteArray(string s)
        {
            byte[] byteArray = new Byte[s.Length];
            for (int index = 0; index < s.Length; index++)
            {
                byteArray[index] = (byte)s[index];
            }
            return byteArray;
        }

public void getEncryptedAssignments()
        {
            //Declare an SQl Command that handles the stored procedure getEncryptedAssignments
            command = new SqlCommand("getEncryptedAssignments", myConnection);
            command.CommandType = CommandType.StoredProcedure;
            myConnection.Open();

            //Declare stored procedure parameters associated with database Assignment Table
            command.Parameters.Add(new SqlParameter("@studentID", SqlDbType.Int, 4, "StudentID"));
            command.Parameters["@studentID"].Value = txt_StudentID_RetrieveAss.Text;

            reader = command.ExecuteReader();
            byte[] blobFile;
            byte[] blobKey;
            string fName;

            string OutFile = @"d:\_DecryptedFile";
            string OutKey = @"d:\_PublicKey";

            //Create a new instance of the FileUpload class to save the encrypted files
            //to the D: drive
            //FileUpload outEncFIle = new FileUpload();
            //outEncFIle.SaveAs(OutFile);

            //Pass the file location stored in OutFile to a byte array.
            //This will be used to get the file from the database.  
            //Likewise for the key file
            //byte[] outFile = …
Elmo_loves_you 20 Junior Poster in Training

thanks Jerry, I found that after I created this thread....It is a very helpful little application. I have tried to implement your code into my asp.net...

but im having a little trouble getting my program to go into my while loop in order to read through the data in the reader returned by the stored procedure...the stored procedure does return the binary blob data that I want however in the code behind its telling me that the reader is null

Elmo_loves_you 20 Junior Poster in Training

There is probably a very simple way to do this.....please help me.

while (reader.Read())
{
//Get the file in bytes from the reader
byte[] blobFile = reader["FileName"] as byte[];

}

What I want to do is force the blobFile to save somewhere now,

Elmo_loves_you 20 Junior Poster in Training

Hi

I was hoping that somebody could help me.

I have a stored procedure that returns blob file and other data. The blob files are encrypted =) in byte form.

what I want to do now is decrypt them for the user to see but in order to do that I need to pass in a string path of where the files are stored. Has anybody any idea how I could programatically force the files returned via the Stored Procedure to save to disk...From here I could use the decryption code I have to pass in the string file paths.

Please help me - - many thanks Michelle

Elmo_loves_you 20 Junior Poster in Training

Hi, I was just wondering if anybody new of a way to store an encrypted file to an sql server database through a stored procedure. I have managed to encrypt a file selected from a FileUpload control but at the minute the encrypted file and the key are created and saved locally to the machine.

What I would like to be able to achieve is: under the one submit button have the file encrypted and then store the encrypted file and key to the database or force user A to browse for these files before submitting.

However, on execution I am getting an error stating that Input string was not in correct format and it is bugging out at the following line:

submitCommand.ExecuteReader();

Below is a section of the code that I am using to try to save the encrypted file and key to the database (as varbinary)

byte[] blobEcryptedFile = FileUpload_EncryptedFile.FileBytes;
            blobFile = blobEcryptedFile;

            byte[] blobPKey = FileUpload_Key.FileBytes;
            blobKey = blobPKey;

//Actual filename of the file
            string filename = FileUpload_submitAss.FileName;

submitCommand.Parameters.Add(new SqlParameter("@assignment", SqlDbType.VarBinary, blobFile.Length, ParameterDirection.Input, false, 0, 0, "Assignment", DataRowVersion.Current, blobFile));
            submitCommand.Parameters["@assignment"].Value = blobFile;  //The path to the encrypted file

            submitCommand.Parameters.Add(new SqlParameter("@filename", SqlDbType.NVarChar, 50, "Filename"));
            submitCommand.Parameters["@filename"].Value = filename;

            submitCommand.Parameters.Add(new SqlParameter("@publicKey", SqlDbType.VarBinary, blobKey.Length, ParameterDirection.Input, false, 0, 0, "pKey", DataRowVersion.Current, blobKey));
            submitCommand.Parameters["@publicKey"].Value = blobKey;    //The path to the key

submitCommand.ExecuteReader();
            submitCommand.Dispose();
            myConnection.Close();

            lbl_validation_submitAssignment.Text = "Your file has successfully been uploaded!";

Has anybody any ideas??

Elmo_loves_you 20 Junior Poster in Training

The following code it what I have for getting the blob from the database based on a value in a textbox.....its pulling out a blob but only the first one in the table.....anyone want to help me get this to loop through the table searching for the correct one

SqlConnection NewConnection = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Assignment_Submissions.mdf;Integrated Security=True;User Instance=True"); //Connection string declared in web.config file
            NewConnection.Open();

            dataAdapter = new SqlDataAdapter("SELECT * FROM Assignment", myConnection);
            SqlCommandBuilder cb = new SqlCommandBuilder(dataAdapter);
            DataSet ds = new DataSet();

            command = new SqlCommand("getBrief", NewConnection);    //getAssBrief
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add(new SqlParameter("@assignmentID", 


SqlDbType.Int, 4, "AssignmentID"));
            command.Parameters["@assignmentID"].Value = txt_AssignmentID_ViewBrief.Text;

            reader = command.ExecuteReader();
            //byte[] myFile;
            string tempFilename = "";
            //string fileType = "";

            //StringBuilder sb = new StringBuilder();
            while (reader.Read())
            {
                tempFilename = reader.GetString(0);
                //sb.Append(reader.GetValue(0));
                //sb.Append(",");

            } //NewConnection.Close();

            myConnection.Open();
            
            dataAdapter.Fill(ds, "Assignment");
           
            DataRow myRow;
            myRow = ds.Tables["Assignment"].Rows[0];

            byte[] myData;
            myData = (byte[])myRow["AssignmentBrief"];

            Response.Buffer = true;
            Response.AddHeader("Content-Disposition", "attachment;filename=" + tempFilename); // + filename
            Response.ContentType = "application/msword";
            Response.BinaryWrite(myData);

            cb = null;
            ds = null;
            dataAdapter = null;
Elmo_loves_you 20 Junior Poster in Training

Im not too sure then, all I need mine to do is give the user the option to open, save or cancel the download.....although at the minute, word is unable to open the file, it cant recognise the file format

Elmo_loves_you 20 Junior Poster in Training

better to store this in a database because that way you wont accidentally delete the file from disk, making the link broken....

I have been working on this, have the BLOB in the database, working on getting it out again now

I just got code working there to get a file back out based on an ID, but its returning the wrong file for that ID :S lol

Elmo_loves_you 20 Junior Poster in Training

Hi,

I have a webpage set up that allows users to upload a file to a server from the fileupload control, which is then saved to the database with the blob file and the file name. What I would like to do now is retrieve this file by selecting a particular value in a dropdown list and clicking on a 'download file' button.

This would then search the database for the ID of the file selected and then throw back the file giving the user the option to 'open, save or cancel'

I have found the following code that retrieves a blob from a database. But this does it only for a specific hardcoded filename. What I have been trying to do is write a stored procedure that takes the ID of the file and returns the BLOB....Its already in the database I just need a little help getting it out now...has anyone any ideas?

SqlDataAdapter da = new SqlDataAdapter("Select * From pub_info", myConnection);
                SqlCommandBuilder MyCB = new SqlCommandBuilder(da);
                DataSet ds = new DataSet();

                myConnection.Open();
                da.Fill(ds, "Pub_info");
                DataRow myRow;
                myRow = ds.Tables["Pub_info"].Rows[0];

                byte[] MyData;
                MyData = (byte[])myRow["logo"];

                Response.Buffer = true;
                //Replace the following commented out line with the lines below for word doc
                //Response.ContentType = "Image/JPEG";
                Response.AddHeader("Content-Disposition", "attachment;filename=blob.doc");
                Response.ContentType = "application/msword";
                
               Response.BinaryWrite(MyData);


                MyCB = null;
                ds = null;
                da = null;

                myConnection.Close();
                myConnection = null;

Please provide some suggestions.
Elmo

Elmo_loves_you 20 Junior Poster in Training

Hi, I have an SQL Server 2005 database set up and I have quite a few stored procedures that I am using to query the database. Basically what I am doing is gathering data from a user on a web form and then processing this data through stored procedures and c# code to upload and retrieve data from the database.

At the beginning my project was running rather efficiently :) however now that it has become slightly larger it has slowed down a great deal. I have been reading threads that say to put the connection string into the web.config file. However, I am not sure how I should go about coding (in terms of opening and closing the connection)

For example, in my web.config file I have the following:

<connectionStrings>
        <add name="AMIS_DBconnection"
             providerName="System.Data.SqlClient"
             connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Assignment_Submissions.mdf;Integrated Security=True;User Instance=True"/>
    </connectionStrings>

and just to illustrate how I am using my code in the code behind pages (with lots more stored procedures):

public void getModule()
        {
            SqlConnection myConnection = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Assignment_Submissions.mdf;Integrated Security=True;User Instance=True"); 

            DD_Module_ViewBrief.Items.Clear();
            command = new SqlCommand("Modules", myConnection);
            command.CommandType = CommandType.StoredProcedure;
            myConnection.Open();

            command.Parameters.Add(new SqlParameter("@CourseCode", SqlDbType.NVarChar, 50, "CourseCode"));
            command.Parameters["@CourseCode"].Value = DD_Course_ViewBrief.SelectedValue;

            reader = command.ExecuteReader();   //CommandBehavior.CloseConnection

            while (reader.Read())
            {
                DD_Module_ViewBrief.Items.Add(new ListItem(reader.GetString(0)));
            }
            reader.Close();
            command.Dispose();
            myConnection.Close();
            myConnection.Dispose();
        }

I am creating a new connection string each time I need to connect to the database to get data but I am also closing and disposing of it too. (Should this not mean that my website should run just as well as it did …

Elmo_loves_you 20 Junior Poster in Training
Byte[] b = FileUpload_uploadBrief.FileBytes;
                        blob = b;

I got it working, the FileUpload was reading bytes already and I had no need to use FileStream class....all hunky dory now (well just that one wee bit)

Elmo_loves_you 20 Junior Poster in Training

I was going to put it there but my problem really isnt ASP its c# .... the FileUpload control can be used in windows forms and asp.net pages so ... plus Im new to this forum and dont know how to move the thread!

Elmo_loves_you 20 Junior Poster in Training

Hi, I would really appreciate some help.

I have a FileUpload control on my Asp.Net web page and want to store the file to a database as a varbinary(max) BLOB with other data via an sproc. However I am getting an error at the line

FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);

ERROR = The given paths format is not supported

I found a sample piece of code that stores a file to a database but it needs a hardcoded File location string (which doesnt quite work with what I want from the fileUpload control). Although I implemented it as a test page and it stores the file (and opens it in another piece of code) just the way I want mine to work.

I know the file from the upload control is already in byte format and that I am creating a new byte array to store the file data but I dont know how to go about doing this other than the way I am currently trying to do it.

protected void Button1_Click(object sender, EventArgs e)
        {
            DateTime now = DateTime.Today.Date;
            DateTime due_date = DateTime.Parse(txt_dueDate_uploadBrief.Text);
            DateTime return_date = DateTime.Parse(txt_ReturnDate_UploadBrief.Text);
            string modID = txt_HiddenModuleID_UplaodBrief.Text.ToString();
            int module_ID = Convert.ToInt32(modID);
            [B]path = "File:" + FileUpload_uploadBrief.FileName;[/B]
            command = new SqlCommand("upload_upBrief", myConnection);
            command.CommandType = CommandType.StoredProcedure;
            myConnection.Open();

            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);             bblob = new byte[fs.Length];
            fs.Read(bblob, 0, bblob.Length);
            fs.Close();

            //Initialising new instances of SqlParameter that declares the data type, size and column name
            //for the data …
Elmo_loves_you 20 Junior Poster in Training

Hi, I am rather new to programming. I have a stored procedure that simply reads a 'CourseCode' from a Course table, the stored procedure code is as follows:

--------------------------------------------
ALTER PROCEDURE dbo.Courses

AS
SELECT CourseCode
FROM Course
RETURN
---------------------------------------------

I have C# code in the code behind page to try and popuate a dropdownlist with a list of CourseCodes, it is as follows:

public void getCourseDropDown()
        {
            try
            {
                command = new SqlCommand("Courses", myConnection);
                myConnection.Open();
                reader = command.ExecuteReader(CommandBehavior.CloseConnection);

                while (reader.Read())
                {
                    DD_Course_uploadBrief.Items.Add(new ListItem(reader("CourseID".ToString())));
                }
                reader.Close();
            }
            catch (Exception objException)
            {
                //Display the exception message 
                string strError = objException.Message;
                if ((objException.InnerException != null))
                {
                    strError += objException.InnerException.Message;
                }
            }
            finally
            {
                // Clean Up 
                reader = null;
            }
        }

------------------------------------------------------------------------------
When I build the asp.net website application I get the following error:

'reader is a field but is used like a method'

I would be very grateful for any help you all may have,

thanks in advance :)

Elmo_loves_you 20 Junior Poster in Training

Remove

RETURN @RoleTitle
and try

Good luck

Thankyou very much, it worked :)

I now have my login page identifying the correct rank .... wooohooo

though thats just one of a million other things I have to do :)

Elmo_loves_you 20 Junior Poster in Training

Hello Everyone :S

I am rather new to ASP.NET. I have an SQL Server 2005 database set up. So far its quite basic with just two tables (UsersLogin, Roles). My aim is to allow users of different ranks to login to the system ie. Admin, Staff etc.

UsersLogin table holds (UserID, Username, Password, RoleID)
Roles table holds (RoleID, RoleTitle)

I have created a stored procedure that returns the roleTitle based on the username and password entered. I was thinking that this approach would enable me to direct the user to the appropriate page for their rank (in the code behind page), the code is as follows:

//-----------------------------Code Sample--------------------------------
CREATE PROCEDURE dbo.ValidateUser
/* Parameters needed to obtain data from user*/
(
@UserName VARCHAR(20) = NULL
@Password VARCHAR(20) = NULL
@RoleTitle VARCHAR(20) = NULL
)
AS
SELECT Roles.RoleTitle
FROM Roles INNER JOIN
UsersLogin ON Roles.RoleID = UsersLogin.RoleID
WHERE (UsersLogin.Username = @UserName) AND (UsersLogin.Password = @Password)
RETURN @RoleTitle

//-----------------------------END Code Sample--------------------------------

I can execute the query successfully within the design wizard and I get the result I want but I can't save the stored procedure. I am prompted with the following Error Message:

Incorrect syntax near '@Password'
Must declare the scalar variable '@UserName'
Must decalre the scalar variable '@RoleTitle'

I have spent some time reading articles and browsing other threads that have suggested using '?' but this hasnt worked.

Elmo_loves_you 20 Junior Poster in Training

Hello everyone,

I just discovered this forum and so far I have found it very helpful :)

I am a soon to be graduate in computer science :) woohoo

Hopefully some of you may be able to help me with some problems that I am likely to come across in the next few weeks...

Thanks Elmo