Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hello, i'm using visual studio 2008 and microsoft SQL server 2008 to create a program for processing student grade, what i want to do is to create a search button.
the program consist of:
database created with SQL
windows form
class to connect SQL and windows form

the function that i want to create is this:
when i type the name of a student in the textbox and clicked the search button in the form it will display all the information on datagridview.

how do i do that?
Posted

1 solution

You can try this code. Do reply by commenting if any problem occurs. Make sure to use the namespaces in your class that handles data operations. Use appropriate table and database name instead of "test" and "master" in SQL Select query and in Fill method of data adapter. Put this method in your class. And invoke it from your form.cs

C#
using System.Data;
using System.Data.SqlClient;

DataSet getDataSet(string Command, string Connection)
{
    SqlDataAdapter sda = new SqlDataAdapter(Command, Connection);
    DataSet ds = new DataSet();
    sda.Fill(ds, "test");
    return ds;
}

private void BGetData_Click(object sender, EventArgs e)
{
    dataGridView1.DataSource = getDataSet("SELECT * FROM test WHERE Name='" + TBName.Text + "'", @"Server=.\SQLEXPRESS; Database=master; Integrated Security=true;").Tables["test"];
}
 
Share this answer
 
v2
Comments
Akshay Raut 1-May-15 3:25am    
Forgot to mention, even if it may be unnecessary - BGetData_Click is button event handler for Search button which is named "BGetData" and TBName is the text box in which user can type name of student to search for.
Richard Deeming 1-May-15 8:23am    
Your code is vulnerable to SQL Injection[^].

NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.
Akshay Raut 20-Jul-15 13:10pm    
@richard oh right. thanks. I will keep that in mind.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900