Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Load the Store Procedure without using EF I Faced this Problem. I want to load the SP list type
Please see the sample below. Its also shows how to read the records from the StoredProcedure execution in your C# Code.
Also its a good practice initiating the SQLConnection and SQLCommand object in Using Block.
using (var conn = new SqlConnection(cnnString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SearchCustomer";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
// Use below line if you want to pass any parameter values to SP.
// cmd.Parameters.AddWithValue("#id", CustomerId);
using (var reader = cmd.ExecuteReader())
{
while(reader.Read())
{
// Read Column based on Column Name. Below sample reads String column
Console.WriteLine(reader.GetString(reader.GetOrdinal("columnName"));
// Read Column based on Column Index. Below sample reads int column
Console.WriteLine(reader.GetInt32(1));
}
}
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm trying to add a record to my database from my website but keep getting this mapping error
No mapping exists from object type System.Web.UI.WebControls.ListItem to a known managed provider native type.
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#strFirstName", txtAddFirstName.Text);
cmd.Parameters.AddWithValue("#strLastName", txtAddLastName.Text);
cmd.Parameters.AddWithValue("#strCity", txtAddCity.Text);
cmd.Parameters.AddWithValue("#intStateID", ddlAddState.SelectedValue);
cmd.Parameters.AddWithValue("#strZip", txtAddZip.Text);
cmd.Parameters.AddWithValue("#intDepartmentID", ddlAddDepartment.SelectedValue);
cmd.Parameters.AddWithValue("#intLevelID", ddlAddLevel.SelectedItem);
cmd.Parameters.AddWithValue("#isActive", chkAddActive.Checked ? 1 : 0);
cmd.Parameters.AddWithValue("#intReasonForTerminationID", ddlAddReasonForTermination.SelectedValue);
cmd.Parameters.AddWithValue("#dtmDateOfTermination", txtAddDateOfTermination.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
This line:
cmd.Parameters.AddWithValue("#intLevelID", ddlAddLevel.SelectedItem);
Returns an object not a value. Try changing it to .SelectedValue;
I would assume that this kind of code
cmd.Parameters.AddWithValue("#intLevelID", ddlAddLevel.SelectedItem);
is something like a LineItem type but not a string and you have to pass a string value to the method
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I did my homework prior to asking this questions. Though, none of the results that google showed functioned .
I have a textbox whose input I wish to validate against a list of values which exist in a column of a table (ASP.NET with C# and SQL Server 2014 Express) . Should user enter some other value, than the error must be displayed.
I have done multiple tryouts with CustomValidator control and one when an event on the Textbox (.TextChanged). But I lost something, may be in the details. Could you give me a practical solution and at best, guide towards a useful online resource to study the connection to databases from asp.net (c#)?
I am aware that I did not catch the subject.
Here is a basic rough version how you could get it done. Can also use a Stored procedure rather than direct..Wasn't sure if you meant after a button was clicked or not, but you can put this in a method and have it return true or false if its valid.
SqlConnection cnn = null;
SqlCommand cmd = null;
SqlDataAdapter sda = null;
DataTable Dt = new Datatable();
cnn = new SqlConnection(strConnectionString);
cmd = new SqlCommand("Select COLUMN FROM WHEREVER WHERE VALUE =#TextboxValue", cnn);
cnn.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#TextboxValue", SqlDbType.VarChar).Value = Textbox.Text;
sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
if (dt.rows.count > 0 )
{
//MATCH FOUND
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have two classes in which the teachers have merged their final projects into one, one class is software engineering and another one is data bases. The thing is that for SE i have to develop a desktop/smartphone app and for DB i have to develop every DB related stuff for that app.
But i have to keep both things separated, i mean i have to keep C# code away from SQL code so i can't do queries or any stuff using selection strings and such, i just have to call stored procedures with said queries from code.
Any idea how could i do that? To summarize i just want to call any code or procedure that i write in sql and store it's values in a variable,object or array.
As i said i cannot use:
string selectstr = "SELECT * FROM students;"
and execute that query, i have to write that in sql and call it from C# and store the values returned.
Stored procedures are called like any other SQL command in C#:
using (SqlCommand cmd = new SqlCommand("MyStoredProcedure", connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#myParameter1", value);
...
using (SqlDataReader reader = cmd.ExecuteReader())
{
...
}
}
The "magic" bit is to set the command type correctly ;-)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Is there a way to do a c# datarow like the below code in a SELECT * query
//Have results like blow
string username = (string)row["username"];
I've tried but all I seem to see is reader or something, witch I know nothing about and don't understand. Can you lead me to some code that will help or give me a example?
DataReader is actually exactly what you need. The 'DataRow' class by itself won't help you; that gets used as part of a more complex solution, the 'DataSet' class (which uses 'DataTable' and that in turn uses 'DataColumn' and 'DataRow'). I don't see many people using 'DataSet'; if you want something complex with drag-and-drop design, you should look at using Entity Framework.
Here is a standard way to read values from SQL in .NET via DataReader (which, no matter what anyone says, is the fastest way to simply read data from a SQL database in .NET):
using (var connection = new SqlConnection("<Your connection string here>")
{
var command = new SqlCommand(
"SELECT username, email FROM users;",
connection);
connection.Open();
var reader = command.ExecuteReader(); // Using the DataReader (specifically, the SqlDataReader)
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("User {0} has email {1}", reader["username"],
reader["email"]);
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
}
MSDN documentation for DataReader
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
1st: Is there any better way to do
sqlcommand object = new sqlcommand("insert into sometable values '" + textboxes.texts "'," + somelabelvalues.text + "')" , connectiondb); //true for update,delete and everything inwhich we want to feed input data into database.
This is not safe. Is there any better way to do this because this was taught in our C# class.
All suggestions are welcome!
Use a SqlParameter
SqlCommand cmd = new SqlCommand("Select * from sometable where value = #value");
cmd.Parameters.AddWithValue("#value", "value");
Cam Bruce is correct, use SqlParameter always. However, I would like to expound on that just a bit.
First of all, you asked if there is "a better way to do this", the answer is Yes - Use parameters. There is another answer however that was addressed in the original comments, there is a different way to do this using Entity Framework. I would say that it's only better in certain situations. If this is your only SQL query in the project, then good lord please do not use Entity Framework as the overhead would be unnecessary.
You can read up on Entity Framework on MSDN
You should also definitely read up on SQL Injection Attacks
Now on to your code. As Cam stated above, use SqlParameter. He did leave out a couple good practices though on properly handing your command and connection.
It is a good practice to wrap both your SqlCommand and SqlConnection in using statements so that when you are finished with the objects, they will be disposed of.
string mySqlCommandText = "INSERT INTO some_table VALUES (#Value1, #Value2, #Value3)";
//Wrap your connection/command in using blocks
using (var conn = new SqlConnection(mySqlConnectionString))
using (var cmd = new SqlCommand(mySqlCommandText, conn))
{
//Add your values to the parameters
//This is how you avoid the SQL Injection attack
cmd.Parameters.AddWithValue("#Value1", myValue1);
cmd.Parameters.AddWithValue("#Value2", myValue2);
cmd.Parameters.AddWithValue("#Value3", myValue3);
conn.Open();
cmd.ExecuteNonQuery();
} //The cmd and conn objects are disposed of here as they are now out of scope.
Yes this way is not safe because of SQLInjection vulnerability...
as Cam Bruce said, you can use command parameters to make it safe and secure...
SqlCommand cmd = new SqlCommand("Select * from sometable where value = #value");
cmd.Parameters.AddWithValue("#Value", "value");
cmd.ExecuteNonQuery();
just that!