Pulling from a database and displaying with c# [closed] - c#

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'm just starting out with server side code and Visual Studio with C#, but something I can't figure out with my googling is how do people use C# and Visual Studio to access a database and pull results and display them on the html documment?
I have an SQL Server 2012, I believe I know how to connect to the database itself, but unless I use classic ASP I don't understand how to pull it from the database and display it using C# and or ASP.NET.

I suggest you start out with Ado.Net. Once you have a good understanding of the principles, look into Entity Framework.

Robin Nadeau is right, what you'll probably want to start with is Ado.Net controls. In reference to your example, how I would go about it is using a DataGridView and binding it with a BindingSource + DataSet. When you drop a DataGridView on the form, it will give you a chance to run through a wizard to easily set up the BindingSource and Dataset.
To filter stuff from there, you'll need to hook up the buttons etc. with code such as this:
bindingSource1.Filter = string.Format("VideoTitle LIKE '{0}'", txtSearch.Text);
Hopefully that helps you get started.

If you are a beginner and don't have enough time to learn a complete framework. I would suggest to use the WebMatrix.Data Wrapper. Life's simple with it. 6 Commands is all you need to know to make 90% of the applications. Just install the Nuget Package and you're good to go.
Those 6 Commands are
1. Open & Close Connection
var db=Database.Open("name of connection string in web.config");
db.Close();
2. SELECT Query
foreach(var row in db.Query("SELECT * FROM tablename")
{
servervariable1=row.column1;
}
3. SELECT Single Row
var row=db.QuerySingle("SELECT * FROM tablename WHERE Key=#0",PassedVariable);
if(row!=null)
{
// do the operation
}
else
{
// handle code if the row is not found
}
4. SELECT Single Value
try{
datatype variable=db.QueryValue("SELECT columnname FROM tablename WHERE Key=#0",Key);
}
catch{
// handle code if row doesn't exists
}
5. INSERT Query
db.Execute("INSERT INTO tablename(column1,column2) Values(#0,#1)",inputvar1,inputvar2);
6. DELETE Query
db.Execute("DELETE * FROM tablename WHERE Key=#0",key);

Related

I'm trying to create a Multiple choice quiz in c#/winforms, using sql to store retrieve the questions [closed]

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 3 years ago.
Improve this question
I wish to create a simple Winforms app that can access questions from a SQL table called "questions table" as well as table called "answersTable". I would then like to assign the question result to a single textbox on screen and have the 3 "answersTable" results be mapped to 3 individual buttons, I have already made all the forms and achieved this using a JOIN query to join my tables and then mapping the controls (by mapping the controls via the dataReader,
i.e
while data.read()
{
button1.text = datareader.getValue(0)
};
my Winforms which I wish to populate from SQL tables
My code to populate the Winforms
This is what I would like to make
However this only works for the last question and answer in the table and gives me no control of displaying the previous or next entry in the questions and answers tables.
My next thought was to try and take the data from the SQL tables add them to a list box and then use the list box to map the questions and answers to my forms controls but am just unsure if this is the best way to go about it.
Any help would be much appreciated.
There is a lot going on with this code. Let me start with your problem and continue with the rest.
The load method. My guess is what you call in the on initialization of the form. You are reading until the last value from the reader and never look back. What you could do instead.
Create a new class QuizQuestion which will depict your database return structure.
pubic class QuizQuestion {
public string Question { get; set; }
public string AnswerA { get; set; }
// continue for the rest
}
Now in your class, create a member
List<QuizQuestion> quizQuestions;
And last in your while datareader clause, create one QuizQuestion object for every row and add it to your list.
This way you will have all the values saved. Now create a function that will get the last index and show the right list item.
Also create an event for each button to use the previous function to go to the next answer.
Don't forget to close the connection object you are creating. Check the keyword using

How to Update database from UI which has many textboxes and CheckBox in asp.net and SQL Server? [closed]

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 5 years ago.
Improve this question
I am new to ASP.net. I have a webform where I have 40 text box 18 drop downs and 29 checkbox. I need to load the all data from these controls to SQL server database table using stored procedure. I dont want to pass all the parameters one by one and update the table.
Is there any other short way to do it? Please help
I am not sure I follow your question here?
The simplest way, would be to do a model object. Create a method that accepts the model object that includes all the data from your form. This methods feeds the stored procedure call.
This is the common way to do it. And the fastest. You need to assign the data to data-fields. There is no way around it really. But of course it can be done in many different ways.
So you want a more specific answer, you will have to elaborate what you mean by:
"I dont want to pass all the parameters one by one and update the
table."
I can't come up with a scenario where it would be desireable to pass each parameter one by one into an update statement...
but you will have to mention each field in your SQL stored procedure, that you want to update.
if that is your only question:
UPDATE table-name
SET column-name = value, column-name = value, ...
WHERE condition
If you have used a model in your view and used Razor syntax to render the relevant controls than if you have a form defined, posting back to the controller that accepts the same model as it's parameter will handle the binding of all the properties back to the model.
You then either parse the model or use the properties and send them down to entity framework, or any other ORM that you might be using, and have it handle the update operation.
[HttpPost]
public ActionResult YourPostMethod(YourModelUsedInView model)
{
// process your model here and send it down to the DB.
}

C# / SQL Server : MVVM insert data into multiple tables [closed]

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 6 years ago.
Improve this question
I work on a small project just to get to understand the mvvm model in C# better.
I work with a Microsoft SQL Server database with three tables: customer, location and address.
Every customer can have one or more locations, and every location has a specific address.
My current thought how to accomplish this:
First insert the customer.
To insert the location, get the highest customer_id and insert the location with the max(customer_id)
Then, to insert the address, get the max(location_id) and insert the address, with the location id
Is there a better way to do this?
I haven't found any tutorial with an example of inserting data into more than one table, especially not using SQL Server.
And my next problem is: what should I bind to my TextBoxes, so that I can insert the content of it?
I thought about having a save button. This button would then execute a method, where I insert the data from the bound TextBoxes. Should I do this with commands, instead of writing a method?
Thanks already!
Sql server has a OUTPUT clause which you can use
something like
INSERT INTO MyTable VALUES({CustomerName})
OUTPUT INSERTED.ID
then you can store the inserted customer's actual ID and do the rest inserts in separate queries.
As for your second question yes you should do it with Command binding to a method in your View model
The most advisable for your situation is to use a transaction.
Example.- https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqltransaction(v=vs.110).aspx

Bulk insert using AddRange in Entity framework [closed]

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 7 years ago.
Improve this question
I am adding multiple entities in the database using AddRange in Entity Framework:
foreach (string tagNumber in notPresent)
{
element = new TagMaster { Name = Guid.NewGuid().ToString(), IsActive = true };
element.TagCollections.Add(new TagCollection { TagNumber = tagNumber });
newTagMasters.Add(element);
}
dbContext.TagMasters.AddRange(newTagMasters);
dbContext.SaveChanges();
What I was expecting is that by adding the complete collection in context using AddRange method, there would be a single query that will be sent to database. But to my surprise, I see multiple insert statements for each record to be inserted.
Any Insights?
The problem you are running in is that sadly the entity framework commands know NO bulk inserts. Instead they generate 1 statement per line that you want to insert.
There is no workaround to this.
The only possiblity to get 1 single statement that does all the inserts is to use specific classes or libraries. As example here SqlBulkCopy which needs no external lib to be downloaded to work.
Here a link to the msdn site:
https://msdn.microsoft.com/de-de/library/system.data.sqlclient.sqlbulkcopy(v=vs.110).aspx
The usage is quite easy. You only give the constructor your connection (after opening it beforehand!) and tell it what it shall write to teh server and what the destination table name is. Then you only need to close the connection afterwards again.
sqlcon.Open();
using (SqlBulkCopy sqlBulkCopyVariable= new SqlBulkCopy(sqlcon))
{
sqlBulkCopyVariable.BulkCopyTimeout = 600; // 10 minutes timeout
sqlBulkCopyVariable.DestinationTableName = "targetTableName";
sqlBulkCopyVariable.WriteToServer(MyData);
}
sqlcon.Close();
The WriteToServer takes DataTable, DataReader or even arrays of DataRow. The exact implementation there would depend on how you want to give the data to it. So far from my personal experience: That class is quite fast and generates only 1 single statement. BUT it is only there for SqlClients. Thus if you have a different client you need to look up which class or external library would be best fitting for you.
I am afraid insertions through Linq is not optimized as you would expect. It does that by multiple insert statements as you observed. You could instead bypass Linq in those cases and use the bulk copying alternatives instead (ie: for MS SQL server use SqlBulkCopy class, for postgreSQL use Copy etc).

Creating an application for Math Practice with ASP.NET [closed]

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 9 years ago.
Improve this question
I am trying a develop a Math Practice web application using ASP.NET (not MVC), which allows Users to perform Multiple choice or simply type an answer, click a button and see answer.
The first idea that comes to mind is simply get permission to use a book, grab all the questions and answers using a DB and display the right answer. But how would I display the answer or the show me how the answer was derived.
My confusion is; how does this work?:
Do I have to write all the formulas and answer myself?
Are there programs for this?
I do not even know where to start.
What I would like to do is have the user select an answer, if the answer is wrong, they can click the show me button.
I am looking to either write this in C#, Visual Basic using JQuery on the front end.
Just need some direction.
Thanks my friends.
When I was in college I had to do something very similar.
What I did is stored expressions 4 + 5; 1 * 6 in database and then pushed those expressions to evaluate on run-time because it is pretty easy in C#.
It takes expression from database 2 + 2
It evaluates the expression on run-time producing result 4
You get your result and show it to user or do whatever with it
More info on how exactly to do that: http://www.c-sharpcorner.com/UploadFile/mgold/CodeDomCalculator08082005003253AM/CodeDomCalculator.aspx
I don't think you need to evaluate a stored expression. Since you just want the user to enter multiple choice or the answer itself, just set up your database as follows:
QuestionAnswers:
ID (uniqueidentifier) (primary)
QuestionText (varchar)
QuestionAnswer (varchar)
ShowMeHowEquation (varchar)
Then, display the ShowMeHowEquation via jQuery like so:
Show Me How
<div class="showMeHowEquation">Database driven contents here...</div>
<script>
$(document).ready(function() {
$('.showMeHow')click(function() {
$(this).next('.showMeHowEquation').slideDown();
});
});
</script>

Categories