Programs
Programs
net framework
Step 1 - Open Visual Studio 2017 and check for the latest framework installed
Open Visual Studio 2017 and open the template for creating a console application.
Here, you should notice that it is showing I can choose .NET Framework 4.6.2 as the
latest version. However, just below the .NET Framework 4.6.2, there is an option to look
for more frameworks.
Click on the link to search for more Frameworks. It opens a web page -- navigate to the
page from where you can download .NET framework 4.7. You'll find that there are 3
options for downloading and installing the .NET framework 4.7. Following is a
screenshot from the same link:
1. Web installer
2. Offline installer
3. Windows Update
First of all, try with Web Installer. Download the Web Installer and run the
downloaded executable file. If it gets installed without any error, then it is okay.
However, if it does not get installed for your Visual Studio 2017, you will see a
warning message, as displayed in the following screenshot.
Then, have patience and be with me. I am going to explain why it is showing this
message. However, if you are getting any other message or exception, then I
recommend you to update your Visual Studio 2017 first and then retry for the same.
Now, try with the Offline Installer. You may get the same message.
Download Windows Update and install it, but still, you may get the same
message.
Step 4 - Check for the latest .NET Framework installed on your computer
So here, you find an ambiguity as you can see that the installer is saying that .NET
Framework 4.7 has been installed already whereas Visual Studio 2017 is showing the
latest .NET Framework as .NET Framework 4.6.2. So, you must be thinking which one
is correct. For that, you have to check the latest version installed on your machine.
There are multiple options to check for the latest version installed on your machine. You
can check with Visual Studio but it is not the correct version, so you can check with
installed files and registry and other configuration options. I would recommend that
rather than going through those options, we can check it with a simple console
application as well.
1. using Microsoft.Win32;
2. using static Microsoft.Win32.RegistryHive;
3. using static Microsoft.Win32.RegistryKey;
4. using static System.Console;
5.
6. namespace CheckFrameworkVersion
7. {
8. class Program
9. {
10. static void Main(string[] args)
11. {
12. using (RegistryKey key = OpenRemoteBaseKey(Local
Machine, "").OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\
NDP\"))
13. {
14. foreach (string version in key.GetSubKeyName
s())
15. {
16. if (version.StartsWith("v"))
17. {
18. RegistryKey versionKey = key.OpenSub
Key(version);
19.
20. if ((string)versionKey.GetValue("Ver
sion", "") == "")
21. {
22. foreach (string subKey in versio
nKey.GetSubKeyNames())
23. {
24. WriteLine($" {subKey} {ver
sionKey.OpenSubKey(subKey).GetValue("Version", "")}");
25. }
26. }
27.
28. }
29. }
30. }
31. }
32. }
33. }
Console Output
As you can see, it shows that .NET Framework 4.7 has installed already. However, I am
not able to see it in Visual Studio 2017. I am already using the latest version of Visual
Studio 2017, so there should not be any reason to update it.
Open Control panel and go installed programs è select Visual Studio 2017 and click on
modify to open Visual Studio installer. There are other options as well to open the Visual
Studio installer.
You can see in the preceding screenshot that there is an option to select/deselect
components.
Please select the options -
You can select only .NET Framework 4.7 but I am selecting both so that I can use both
of them interchangeably.
Once installation gets completed, please open Visual Studio 2017 and check for
the .NET Framework in the drop-down list, as shown in the below screenshot.
So, you can see in the screenshot that .NET Framework 4.7 has installed and available
for use in Visual Studio 2017. If your machine has Visual Studio 2015 & Visual Studio
2013 as well, then Microsoft.NET Framework 4.7 gets installed for those versions as
well.
So finally, .NET Framework 4.7 has installed for Visual Studio 2013, 2015, & 2017.
1. Open Visual Studio 2017 (version 15.3.5 or later) => File => New Project =>
Web => ASP.NET Core Web Application.
2. Select .NET Framework 4.7 & ASP.NET Core Web Application, as shown in the
following screenshot.
3. Click on the OK button.
4. It opens a new window where you can choose different versions of ASP.NET
Core.
As you can see in the above screenshot, there are two versions of ASP.NET Core are
available.
Though ASP.NET Core 2.0 is not available in the dropdown list. You can see in the
screenshot that there is an option for downloading .NET Core 2.0. Click on the
download link to download it.
First You need to download Visual Studio 2013 Ultimate version from Microsoft
Download Page . Here I am using Ultimate version of Visual Studio which is a Licensed
Version. You might want to use Community version or trial version for your demo
purposes. You can use any version as per your requirement. The main difference will
comes in terms of features available in each version.
Once the software is downloaded, you can extract and double click
on vs_ultimate.exe file. Please be sure to start the installation with admin access to
avoid any unnecessary permission issue.
Step 3: Click on Install
You can click on I agree radio button and then click on Next. Here you can custom
select the number of features you want to install along with Visual Studio. It is not
necessarily important to select all the features now itself. You can also later install these
features as per your requirement. For this demo, I will use the default selected features
and Click on Install.
Step 4: Installation Started
Now you can see that it calculates the amount of space required and check the amount
space available and will start the installation process.
Advertisements
Step 5: Successful Installation
Entire Installation process takes around 15-20 mins usually depends on number of
features you have selected. Once it completes without any error then you will be see
below setup successful Screen. Now You can Launch Visual Studio 2013 by Clicking
on Launch.
Step 6: Open a New Project
It is now time to create a Sample Application. You can select New Project->Console
Application and select the Language as Visual C# from left template window. You
can provide the name of the Project and specify the project location. In this demo, I am
using default setting as you can see below.
Step 7: Write Your First Hello World Program
Once all the options are set, you can see a default application created with some default
code. If you can notice, below are the default system namespaces it already provides.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
This is a simple program to display Hello World in the Output. As you can see in below
program, Console.WriteLine() method is used to display Hello, World in the
standard output. This program has starting point from main() function like it usually
happens in other programming language as well. Now you can Build your application by
using Debug->Start without Debugging.
If the project build is successful and there is no error, then you will see below output
screen with output Hello World. To exit out from this screen, you can click any Key.
3. Hello world in visual studio
Output:
Hello World!
4. GUI form design for studentattendence
5. The today’s attendance is only visible to teachers. When the teacher log into the
system, his or her students are listed automatically. The teacher can browse through
the student data and mark attendance.
6. System Diagram for Today’s Attendance
// management system
import javax.swing.*;
import java.awt.*;
import java.awt.Image;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.*;
import javafx.print.Printer;
import java.io.*;
import java.io.IOException;
rb7;
JFileChooser f1;
// Default constructor to
fee()
l2 = new JLabel(
"Name of the Student:");
l3 = new JLabel(
l7 = new JLabel("Address:");
l9 = new JLabel("Gender:");
l9.setBounds(50, 500, 250, 20);
JRadioButton r5
JRadioButton r6
bg.add(r5);
bg.add(r6);
String language[]
= new JComboBox(language);
String languagess[]
JLabel l15
= new JComboBox(languagess);
l8 = new JLabel(
bg1.add(rb1);
bg1.add(rb2);
rb3 = new JRadioButton("HOSTELLER");
bg2.add(rb3);
bg2.add(rb4);
String languages[]
"CIVIL", "MECH" };
final JComboBox cb
= new JComboBox(languages);
= new DefaultListModel<>();
= new JList<>(li1);
= new DefaultListModel<>();
li2.addElement(
li2.addElement(
li2.addElement(
li2.addElement(
li2.addElement(
"bus(40, 000)");
= new JList<>(li2);
list2.setBounds(
add(l1);
add(l2);
add(l3);
add(l4);
add(l5);
add(l6);
add(l7);
add(l8);
add(l9);
add(l10);
add(l11);
add(l12);
add(l13);
add(l14);
add(tf1);
add(tf2);
add(tf3);
add(tf4);
add(tf5);
add(tf6);
add(tf7);
add(tf8);
add(area1);
add(area2);
add(l15);
add(rb1);
add(rb2);
add(rb3);
add(rb4);
add(r5);
add(r6);
add(cb);
add(cb1);
add(cb2);
add(list1);
add(list2);
add(b);
add(label);
add(Receipt);
add(b2);
add(Print);
b.addActionListener(new ActionListener() {
if (list1.getSelectedIndex() != -1) {
+ list1.getSelectedValue();
label.setText(data);
if (list2.getSelectedIndex() != -1) {
list2.getSelectedValues()) {
label.setText(data);
});
// Reset the text fields
b2.addActionListener(
new ActionListener() {
ActionEvent e)
area2.setText("");
area1.setText(" ");
tf1.setText("");
tf2.setText("");
tf3.setText("");
tf4.setText("");
tf5.setText("");
tf6.setText(" ");
});
new ActionListener() {
ActionEvent e)
try {
area2.print();
catch (java.awt.print
.PrinterException a) {
System.err.format(
"NoPrinter Found",
a.getMessage());
});
Receipt.addActionListener(new ActionListener() {
area2.setText(
"--------------------------------"
+ "-----------FEE RECEIPT----"
+ "--------------------------"
+ "--------------------------"
+ "-------------------\n");
area2.setText(area2.getText()
+ tf1.getText()
+ "\n");
area2.setText(area2.getText()
+ tf2.getText()
+ "\n");
area2.setText(area2.getText()
+ "RollNumber: "
+ tf3.getText()
+ "\n");
area2.setText(area2.getText()
+ tf4.getText()
+ "\n");
area2.setText(area2.getText()
+ tf5.getText()
+ "\n");
area2.setText(area2.getText()
+ cb.getSelectedItem()
.toString()
+ "\n");
if (rb1.isSelected()) {
area2.setText(area2.getText()
if (rb2.isSelected()) {
area2.setText(area2.getText()
if (rb3.isSelected()) {
area2.setText(area2.getText()
+ "Wants to be a "
+ "Hosteller \n");
if (rb4.isSelected()) {
area2.setText(area2.getText()
+ "Wants to be a "
area2.setText(area2.getText()
.toString()
+ "\n");
area2.setText(area2.getText()
+ list2.getSelectedValue()
.toString()
+ "\n");
if (index2 == 0) {
area2.setText(area2.getText()
+ " "
if (index2 == 1) {
area2.setText(area2.getText()
+ " "
if (index2 == 2) {
area2.setText(area2.getText()
+ " "
if (index2 == 3) {
area2.setText(area2.getText()
+ " "
}
if (index2 == 4) {
area2.setText(area2.getText()
+ " "
if (e.getSource() == Receipt) {
try {
FileWriter fw
= new FileWriter(
"java.txt", true);
fw.write(area2.getText());
fw.close();
System.out.println(ae);
}
JOptionPane.showMessageDialog(
};
});
addWindowListener(
new WindowAdapter() {
WindowEvent we)
System.exit(0);
});
setSize(800, 800);
setLayout(null);
setVisible(true);
setBackground(Color.cyan);
{
new fee();
Output:
When all the details are added in the respective fields:
When the receipt button is pressed:
When the data is stored in a text file:
When print button is clicked, the following options are shown. If the printer is
available, then it can be directly printed.
Preview of the document if the printer is available:
5.
6. <!DOCTYPE html>
7. <html>
8. <body>
9.
10. <form>
11. Username:<br>
12. <input type="text" name="username">
13. <br>
14. Email id:<br>
15. <input type="text" name="email_id">
16. <br><br>
17. <input type="submit" value="Submit">
18. </form>
19.
20. </body>
21. </html>
Output :
1.
Text Field in HTML Forms :
The text field is a one line input field allowing the user to input text. Text
Field input controls are created using the “input” element with a type attribute
having value as “text”.
html
<!DOCTYPE html>
<html>
<body>
<form>
</form>
</body>
</html>
1. Output :
html
<!DOCTYPE html>
<html>
<body>
<form>
<label for="user-password">Password:
</label><br>
id="user-password">
</form>
</body>
</html>
Output
html
<!DOCTYPE html>
<html>
<body>
<form>
SELECT GENDER
<br>
<label for="male">Male</label><br>
<label for="female">Female</label>
</form>
</body>
</html>
output
html
<!DOCTYPE html>
<html>
<body>
<form>
<b>SELECT SUBJECTS</b>
<br>
<label for="maths">Maths</label>
<label for="science">Science</label>
<label for="english">English</label>
</form>
</body>
</html>
1. Output :
<!DOCTYPE html>
<html>
<h3>Example of a File Select Box</3>
<body>
<form>
<label for="fileselect">Upload:</label>
<input type="file" name="upload" id="fileselect">
</form>
</body>
</html>
Output :
<!DOCTYPE html>
<html>
<h3>Example of a Text Area Box</h3>
<body>
<form>
<label for="Description">Description:</label>
<textarea rows="5" cols="50" name="Description"
id="Description"></textarea>
</form>
</body>
</html>
Output :
<!DOCTYPE html>
<html>
<h3>Example of a Select Box</h3>
<body>
<form>
<label for="country">Country:</label>
<select name="country" id="country">
<option value="India">India</option>
<option value="Sri Lanka">Sri Lanka</option>
<option value="Australia">Australia</option>
</select>
</form>
</body>
</html>
Output :
Reset And Submit Buttons :
The Submit Button allows the user to send the form data to the web server. The Reset Button is
used to reset the form data and use the default values.
<!DOCTYPE html>
<html>
<h3>Example of a Submit And Reset Button</h3>
<body>
<form action="test.php" method="post" id="users">
<label for="username">Username:</label>
<input type="text" name="username" id="Username">
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</body>
</html>
Output :
Attributes Used in HTML Forms
<!DOCTYPE html>
<html>
<h3>Example of a Submit And Reset Button</h3>
<body>
<form action="test.php" method="post" id="users">
<label for="username">Username:</label>
<input type="text" name="username" id="Username">
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</body>
</html>
If you click the submit button, the form data
would be sent to a page called test.php .
The Target Attribute in HTML Forms :
The Target attribute is used to specify whether the submitted result will open in the current
window, a new tab or on a new frame. The default value used is “self” which results in the form
submission in the same window. For making the form result open in a new browser tab, the
value should be set to “blank”.
<!DOCTYPE html>
<html>
<body>
<form action="/test.php" target="_blank">
Username:<br>
<input type="text" name="username">
<br>
Password:<br>
<input type="password" name="password">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
After clicking on the submit button, the result
will open in a new browser tab.
Name Attribute in Html Forms :
The name attribute is required for each input field. If the name attribute is not specified in an
input field then the data of that field would not be sent at all.
<!DOCTYPE html>
<html>
<body>
</body>
</html>
In the above code, after clicking the submit button, the form data will
be sent to a page called /test.php. The data sent would not include the
username input field data since the name attribute is omitted.
The Method Attribute :
It is used to specify the HTTP method used to send data while submitting the form.There are
two kinds of HTTP Methods, which are GET and POST.
The GET Method –
<!DOCTYPE html>
<html>
<body>
</body>
</html>
In the GET method, after the submission of the form, the form values
will be visible in the address bar of the new browser tab.
The Post Method –
<!DOCTYPE html>
<html>
<body>
</body>
</html>
In the post method, after the submission of the form, the form values
will not be visible in the address bar of the new browser tab as it was
visible in the GET method.
Program 6 For loops execution for drop downlist
Adding (Inserting) item in ASP.Net DropDownList using For Loop in C# and VB.Net
Inside the Page Load event of the page, an ArrayList (Array) is populated with the some string values of Customer
names.
First a blank (empty) item is inserted at the first position and then a loop is executed over the ArrayList items and
one by one each item is added to the DropDownList.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
ArrayList customers = new ArrayList();
customers.Add("John Hammond");
customers.Add("Mudassar Khan");
customers.Add("Suzanne Mathews");
customers.Add("Robert Schidner");
C# while Loop
int i = 0; // initialization
i++; // increment
}
Try it
Output:
i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
Above, a while loop includes an expression i < 10. Inside a while loop,
the value of i increased to 1 using i++. The above while loop will be
executed when the value of i equals to 10 and a condition i <
10 returns false.
Use the break or return keyword to exit from a while loop on some
condition, as shown below.
while (true)
{
Console.WriteLine("i = {0}", i);
i++;
if (i > 10)
break;
}
Try it
while (i > 0)
{
Console.WriteLine("i = {0}", i);
i++;
}
while (i < 2)
{
Console.WriteLine("i = {0}", i);
i++;
while (j < 2)
{
Console.WriteLine("j = {0}", j);
j++;
}
}
Try it
Output:
i = 0
j = 1
i = 1
Secondly, we will create a new project and choose console application in C# and give a
name to the project as SqlConnectionDemo, and write the following code in our
program.cs
1. using System;
2. using System.Data.SqlClient;
3.
4. namespace SqlConnectionDemo
5. {
6. /// <summary>
7. ///ADO.NET is an object oriented libraries that allows us to
interact with database and we weill learn how to connect with sql
database using ADO.NET
8. /// </summary>
9. class Program
10. {
11. public void SelectData()
12. {
13. // Create object(instance) of sql connection whi
ch will provide a connection to the data source(database) to read
and write database
14. SqlConnection cn = new SqlConnection(@"data sour
ce=DESKTOP-6DF0CN3\SQLEXPRESS; Database=EmployeeDatabase; integra
ted security = true");
15. // Sql command allow data adpeters to read, add,
update and delete the records in a data source.
16. // Data adapters support 4 properties that give
us access to these objects - select, insert, update adn delete fo
r creating queries to database.
17. // Sqlcommand perform a query on the EmployeeDet
ails
18. SqlCommand cmd = new SqlCommand("select * from E
mployeeDetails", cn);
19. // Open the connection by calling open() method
of sqlconnection object cn
20. cn.Open();
21. //holds a read only, forward only set of data fr
om a database.
22. //using a sql Data Reader can increase speed bec
ause only one row of data is in memory at a time.
23. // result set is returned as SqlDataReader
24. SqlDataReader rdr = cmd.ExecuteReader();
25. // While Loop Read the first column from each ro
w of result set which is employee name
26. while (rdr.Read())
27. {
28. // Print employee details
29. Console.WriteLine(rdr[0] + " " + rdr[1] + " " + r
dr[2]+ " " + rdr[3]);
30. }
31. // Close the reader by calling CLose() method
32. rdr.Close();
33. // Close the connection by calling close() metho
d
34. cn.Close();
35. }
36. static void Main(string[] args)
37. {
38. // Create the object of Program class P
39. Program p = new Program();
40. // invoke the SelectData () Method
41. p.SelectData();
42. Console.ReadLine();
43. }
44. }
45. }
Output
create
While loop
The while loop is used for iterative purposes. Suppose if you want to repeat a
certain set of statements for a particular number of times, then while loop is
used.
In our example below, we use the while statement to display the value of a
variable ‘i’. The while statement is used to display the value 3 times.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DemoApplication
{
class Program
{
static void Main(string[] args)
{
Int32 value=3,i=0;
while(i<value)
{
Console.WriteLine(i);
i=i+1;
}
Console.ReadKey();
}
}
}
Code Explanation:-
1. Two Integer variables are defined, one being value and the other being
‘i’. The value variable is used as the upper limit to which we should
iterate our while statement. And ‘i’ is the variable which will be
processed during the iteration.
2. In the while statement, the value of ‘i’ is constantly checked against the
upper limit.
3. Here we display the value of ‘i’ to the console. We also increment the
value of ‘i’.
If the above code is entered properly and the program is executed
successfully, the following output will be displayed.
Output:
Here you can see that the while statement is executed 3 times and
incremented at the same time. And each time, it displayed the current value of
the variable ‘i’.
o connect with SQL Server, we must have it installed in our system. We are using
Microsoft SQL Server Management Tool to connect with the SQL Server. We can use this
tool to handle database. Now, follow the following steps to connect with SQL Server.
It will prompt for database connection. Provide the server name and
authentication.
After successful connection, it displays the following window.
2. Creating Database
Now, create database by selecting database option then right click on it. It pops
up an option menu and provides couple of options.
Click on the New Database then it will ask for the database name. Here, we have
created a Student database.
Click on the Ok button then it will create a database that we can see in the left
window of the below screenshot.
3. Establish connection and create a table
After creating database, now, let's create a table by using the following C# code.
In this source code, we are using created student database to connect.
In visual studio 2017, we created a .NET console application project that contains
the following C# code.
// Program.cs
1. using System;
2. using System.Data.SqlClient;
3. namespace AdoNetConsoleApplication
4. {
5. class Program
6. {
7. static void Main(string[] args)
8. {
9. new Program().CreateTable();
10. }
11. public void CreateTable()
12. {
13. SqlConnection con = null;
14. try
15. {
16. // Creating Connection
17. con = new SqlConnection("data source=.; database=student; integrate
d security=SSPI");
18. // writing sql query
19. SqlCommand cm = new SqlCommand("create table student(id int not
null,
20. name varchar(100), email varchar(50), join_date date)", con);
21. // Opening Connection
22. con.Open();
23. // Executing the SQL query
24. cm.ExecuteNonQuery();
25. // Displaying a message
26. Console.WriteLine("Table created Successfully");
27. }
28. catch (Exception e)
29. {
30. Console.WriteLine("OOPs, something went wrong."+e);
31. }
32. // Closing the connection
33. finally
34. {
35. con.Close();
36. }
37. }
38. }
39. }
Execute this code using Ctrl+F5. After executing, it displays a message to the
console as below.
We can see the created table in Microsoft SQL Server Management Studio also. It
shows the created table as shown below.
See, we have a table here. Initially, this table is empty so we need to insert data
into it.
// Program.cs
1. using System;
2. using System.Data.SqlClient;
3. namespace AdoNetConsoleApplication
4. {
5. class Program
6. {
7. static void Main(string[] args)
8. {
9. new Program().CreateTable();
10. }
11. public void CreateTable()
12. {
13. SqlConnection con = null;
14. try
15. {
16. // Creating Connection
17. con = new SqlConnection("data source=.; database=student; integrate
d security=SSPI");
18. // writing sql query
19. SqlCommand cm = new SqlCommand("insert into student
20. (id, name, email, join_date)values('101','Ronald Trump','ronald@exampl
e.com','1/12/2017')", con);
21. // Opening Connection
22. con.Open();
23. // Executing the SQL query
24. cm.ExecuteNonQuery();
25. // Displaying a message
26. Console.WriteLine("Record Inserted Successfully");
27. }
28. catch (Exception e)
29. {
30. Console.WriteLine("OOPs, something went wrong."+e);
31. }
32. // Closing the connection
33. finally
34. {
35. con.Close();
36. }
37. }
38. }
39. }
Execute this code by using Ctrl+F5 and it will display the following output.
5. Retrieve Record
Here, we will retrieve the inserted data. Look at the following C# code.
// Program.cs
1. using System;
2. using System.Data.SqlClient;
3. namespace AdoNetConsoleApplication
4. {
5. class Program
6. {
7. static void Main(string[] args)
8. {
9. new Program().CreateTable();
10. }
11. public void CreateTable()
12. {
13. SqlConnection con = null;
14. try
15. {
16. // Creating Connection
17. con = new SqlConnection("data source=.; database=student; integrate
d security=SSPI");
18. // writing sql query
19. SqlCommand cm = new SqlCommand("Select * from student", con);
20. // Opening Connection
21. con.Open();
22. // Executing the SQL query
23. SqlDataReader sdr = cm.ExecuteReader();
24. // Iterating Data
25. while (sdr.Read())
26. {
27. Console.WriteLine(sdr["id"] + " " + sdr["name"]+" "+sdr["email"]); //
Displaying Record
28. }
29. }
30. catch (Exception e)
31. {
32. Console.WriteLine("OOPs, something went wrong.\n"+e);
33. }
34. // Closing the connection
35. finally
36. {
37. con.Close();
38. }
39. }
40. }
41. }
Execute this code by Ctrl+F5 and it will produce the following result. This
displays two records, one we inserted manually.
Output:
6. Deleting Record
This time student table contains two records. The following C# code delete one row
from the table.
// Program.cs
1. using System;
2. using System.Data.SqlClient;
3. namespace AdoNetConsoleApplication
4. {
5. class Program
6. {
7. static void Main(string[] args)
8. {
9. new Program().CreateTable();
10. }
11. public void CreateTable()
12. {
13. SqlConnection con = null;
14. try
15. {
16. // Creating Connection
17. con = new SqlConnection("data source=.; database=student; integrated secur
ity=SSPI");
18. // writing sql query
19. SqlCommand cm = new SqlCommand("delete from student where id = '101'",
con);
20. // Opening Connection
21. con.Open();
22. // Executing the SQL query
23. cm.ExecuteNonQuery();
24. Console.WriteLine("Record Deleted Successfully");
25. }
26. catch (Exception e)
27. {
28. Console.WriteLine("OOPs, something went wrong.\n"+e);
29. }
30. // Closing the connection
31. finally
32. {
33. con.Close();
34. }
35. }
36. }
37. }
Output:
26.9M
603
C++ vs Java
1. TestEntities proxy;
5. AttachTo method is used when an entity exists in the store already and you would
want the DataServiceContext to track that entity. Use AddObject or AddTo method
when a new entity is created and want the Context to track the entity. Write the Event
Handelers for DataGrid Events
6. Create a ObservableCollection
1. /// <summary>
2. /// Represents a dynamic data collection that provides notificati
ons when items get added, removed, or when the whole list is refr
eshed.
3. /// </summary>
4. ObservableCollection < Users > BoundData {
5. get {
6. return (dataGrid.ItemsSource as ObservableCollection < Users
> );
7. }
8. }
1. [global::System.Data.Services.Common.DataServiceKeyAttribute("Use
rID")]
2. public partial class Users {
3. /// <summary>
4. /// Create a new Users object.
5. /// </summary>
6. /// <param name="userID">Initial value of UserID.</param>
7. public static Users CreateUsers(int userID) {
8. Users users = new Users();
9. users.UserID = userID;
10. return users;
11. }...
12. to[global::System.Data.Services.Common.DataServiceKeyAttri
bute("UserID")]
13. public partial class Users: System.ComponentModel.INotifyP
ropertyChanged {
14. public event System.ComponentModel.PropertyChangedEventH
andler PropertyChanged;
15.
16. protected virtual void OnPropertyChanged(string property
Name) {
17. if (PropertyChanged != null) {
18. PropertyChanged(this, new System.ComponentModel.Prop
ertyChangedEventArgs(propertyName));
19. }
20. }
21. /// <summary>
22. /// Create a new Users object.
23. /// </summary>
24. /// <param name="userID">Initial value of UserID.</
param>
25. public static Users CreateUsers(int userID) {
26. Users users = new Users();
27. users.UserID = userID;
28. return users;
29. }...
That's all. You are done. Build and run the application.
Step 2
Just Ignore the built-in Models and Controllers and make your own model.
Step 3
Let's create another model by inheriting the DbContext. It is a class that manages all the
database operations, like database connection, and manages various entities of the
Entity Model.
Add "using System.Data.Entity;" that provides access to the core functionality of the
entity framework.
Step 4
Now create a controller to written the code for inserting data into database, displaying
data into view.
Here I am creating "Student" controller. Inside the Controller, I am creating an object of
StudentContext for inserting and retrieving data from database. Also add the necessary
namespace.
Step 5
Now I'm creating the action methods for Inserting and retrieving the data to/from the
database.
Here I am creating an [HttpPost] action method "createStudent" for inserting the JSON-
Formatted data to database. I am Using [HttpPost] attribute to Save/Post the data as
below:
1. [HttpPost]
2. public ActionResult createStudent(Student std)
3. {
4. context.Students.Add(std);
5. context.SaveChanges();
6. string message = "SUCCESS";
7. return Json(new { Message = message, JsonRequestBehav
ior.AllowGet });
8. }
Similarly, I am also creating JSON method "getStudent" to retrieve data from database
and returning raw JSON data to be consumed by JavaScript in view as shown below,
1. public JsonResult getStudent(string id)
2. {
3. List<Student>students = new List<Student>();
4. students = context.Students.ToList();
5. return Json(students, JsonRequestBehavior.AllowGet);
6. }
Step 6
Now add a view to display the data and data inserting field. Here, I am adding a view
named "Index.cshtml". Then, write the HTML codes for making the data input field,
submit button and also for displaying the data in same page. You can use bootstrap
classes for designing. Here I am using bootstrap. My designing code is as below:
1. <div class="col-md-12">
2. <div class="panel panel-primary">
3. <div class="panel-heading">
4. <h3 class="panel-title">Please enter the details belo
w.</h3>
5. </div>
6. <div class="panel-body">
7. <div class="form-group col-md-5">
8. <label>Student Name</label>
9. <input type="text" name="StudentName" id="Student
Name" class="form-control" placeholder="Enter Student Name" requi
red="" />
10. </div>
11. <div class="form-group col-md-5">
12. <label>Student Address</label>
13. <input type="text" name="StudentAddress" id=
"StudentAddress" class="form-control" placeholder="Enter Student
Address" required="" />
14. </div>
15.
16. <div class="form-group col-md-1">
17. <div style="float: right; display:inline-
block;">
18. <input class="btn btn-primary" name="sub
mitButton" id="btnSave" value="Save" type="button">
19. </div>
20. </div>
21. </div>
22. </div><hr />
23. <table id="tblStudent" class="table table-bordered table
-striped table-responsive table-hover">
24. <thead>
25. <tr>
26. <th align="left" class="productth">ID</th>
27. <th align="left" class="productth">Student N
ame</th>
28. <th align="left" class="productth">Student A
ddress</th>
29. </tr>
30. </thead>
31. <tbody></tbody>
32. </table>
33. </div>
We can simply use the bootstrap class and call jQuery functions in ASP.NET MVC
because during the project creation it will by default added to project and also linked to
the template.
Step 7
Now I will write the script for inserting the data as well as retrieving and displaying it to
the view. Just after the HTML code finished add the script shown below,
1. @section Scripts
2. {
3. <script type="text/javascript">
4. $(function () {
5. LoadData();
6. $("#btnSave").click(function () {
7. //alert("");
8. var std = {};
9. std.studentName = $("#StudentName").val();
10. std.studentAddress = $("#StudentAddress").val();
11. $.ajax({
12. type: "POST",
13. url: '@Url.Action("createStudent")',
14. data: '{std: ' + JSON.stringify(std) + '}',
15. dataType: "json",
16. contentType: "application/json; charset=utf-
8",
17. success: function () {
18. // alert("Data has been added successfull
y.");
19. LoadData();
20. },
21. error: function () {
22. alert("Error while inserting data");
23. }
24. });
25. return false;
26. });
27. });
28.
29. function LoadData() {
30. $("#tblStudent tbody tr").remove();
31. $.ajax({
32. type: 'POST',
33. url: '@Url.Action("getStudent")',
34. dataType: 'json',
35. data: { id: '' },
36. success: function (data) {
37. var items = '';
38. $.each(data, function (i, item) {
39. var rows = "<tr>"
40. + "<td class='prtoducttd'>" + item.stude
ntID + "</td>"
41. + "<td class='prtoducttd'>" + item.stude
ntName + "</td>"
42. + "<td class='prtoducttd'>" + item.stude
ntAddress + "</td>"
43. + "</tr>";
44. $('#tblStudent tbody').append(rows);
45. });
46. },
47. error: function (ex) {
48. var r = jQuery.parseJSON(response.responseTe
xt);
49. alert("Message: " + r.Message);
50. alert("StackTrace: " + r.StackTrace);
51. alert("ExceptionType: " + r.ExceptionType);
52. }
53. });
54. return false;
55. }
56. </script>
57. }
We are using Ajax to refresh "tblStudent" so it refreshes only the particular table, rather
than refreshing entire page. After clicking the "submitButton" the data from the input
fields are taken in variable and redirected to action "createStudent" of
"StudentController" to insert into the database. And, I have written a function
"LoadData" to display the data from database to view continuously after inserting data.
Inside "LoadData" function I am calling "getStudent" method which returns result in
JSON and the JSON-Formatted data are presented in html by the underlying
statements.
Step 8
1. <connectionStrings>
2. <add name="StudentContext" connectionString="Data Source=RAVI
-KANDEL;Initial Catalog=Student;Integrated Security=True"
3. providerName="System.Data.SqlClient" />
4. </connectionStrings>
You can add the records and can see added data in the table after the form-control as
shown below,