Visual C# 2012 Chapter 22 Exercise 6. 22.6 (Baseball Database App ) Build an app
ID: 3838185 • Letter: V
Question
Visual C# 2012 Chapter 22 Exercise 6.
22.6 (Baseball Database App) Build an app that executes a query against the Players table of the Baseball database included in the Databases folder with this chapter’s examples. Display the table in a DataGridView, and add a TextBox and Button to allow the user to search for a specific player by last name. Use a Label to identify the TextBox. Clicking the Button should execute the appropriate query. Also, provide a Button that enables the user to return to browsing the complete set of players.
Explanation / Answer
using System; using System.Data; using System.Drawing; using System.Windows.Forms; using System.Data.SqlClient; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) //Front End of the applicaton { label1.Text = "Base ball Players Application"; label1.BorderStyle = BorderStyle.FixedSingle; label1.TextAlign = ContentAlignment.MiddleCenter; button1.Text = "View"; button2.Text = "Search"; textBox1.Width = 250; textBox1.Height = 50; } private void button1_Click(object sender, EventArgs e) // To display table in Datagridview { string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True"; string sql = "SELECT * FROM bplayers"; SqlConnection connection = new SqlConnection(connectionString); SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection); DataSet ds = new DataSet(); connection.Open(); dataadapter.Fill(ds, "bplayers"); connection.Close(); dataGridView1.DataSource = ds; dataGridView1.DataMember = "bplayers"; } private void button2_Click(object sender, EventArgs e) // To search a player { string connetionString = null; SqlConnection connection ; SqlCommand command ; SqlDataAdapter adapter = new SqlDataAdapter(); DataSet ds = new DataSet(); DataView dv ; string sql = null; string var; var = textBox1.Text; connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"; sql = "Select * from bplayers"; connection = new SqlConnection(connetionString); try { connection.Open(); command = new SqlCommand(sql, connection); adapter.SelectCommand = command; adapter.Fill(ds, "Find Row DataView"); adapter.Dispose(); command.Dispose(); connection.Close(); dv = new DataView(ds.Tables[0]); dv.Sort = "Player_Name"; int index = dv.Find("var"); if (index == -1) { MessageBox.Show ("Item Not Found"); } else { MessageBox.Show(dv[index]["Player_id"].ToString() + " " + dv[index]["Player_Name"].ToString()); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } } }
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.