i am newbie in C#. i would like to make a button to function as search button to search by name and search by date. When i key in data inside textbox1 for search by name ,then press search ,can get the data from database. Same case to textbox2 for search by date, then press search. Besides, i can use both textbox to search my database at the same time. Example ,i key in name n date together to find a book that i bought ,then press search button. Please help me. i am no idea how to start.

>Besides, i can use both textbox to search my database at the same time.

if you can search your database, what is the question?

>Besides, i can use both textbox to search my database at the same time.

if you can search your database, what is the question?

sorry. i mean i want to search from my database. i not yet start with the code

asking this kind of questions is not good. you are not stuck with a problem. you need to grab an ado.net book and read first. or basically go to windowsclient.net and watch video tutorials to learn about datadriven applications. i dont want to write code sample for this because there are milions of them out there. the concepts you are looking for are these : System.Data, System.Data.SqlClient name spaces. then you need SqlConnection and or SqlDataAdapter objects. SqlCommand object maybe. then you need to write your Select statement using SqlParameter object(it will prevent sql injection attacks).

Hi,

What you need to do is to build your database, after its ready start working on your program.

When you start working on your program, put on your form two textbox and two buttons (when you have different search engine its better to work with different controls for each engine).

Give the textboxs and the buttons names that defined them,
after that press double click on the first button, it will create for you the event method to be fired when the user will press the button, when you have this event method write the code inside.
The code needs to be somthing like that if you using SQL server database:

"SELECT * FROM BOOK_DB WHERE BookName =" + nameOfNameTextBox.Text.ToString()

or

"SELECT * FROM BOOK_DB WHERE BookDate =" + nameOfDateTextBox.Text.ToString()

If not and you dont know how to build your select function for yours database so ask us.

I assum that you know where the querys need to go but if you dont so ask and we will help you.

Of course its just en example and you need to change the query to your needs, but as i said above if you need any help on that two, so ask and we will help you!

tq for ur reply. i dont really know how the search engine concept work. pls help me recorrect my code below. thank you in advance.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;

namespace WindowsFormsApplication7
{
public partial class Form7 : Form
{
public Form7()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{

SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = ConfigurationManager.ConnectionStrings["myConn"].ToString();

myConn.Open();

if (txtTitle.Text != "")
{
SqlCommand cmd = new SqlCommand("SELECT * from book WHERE title = '" + txtTitle.Text.ToString());

SqlDataReader dr;
dr = cmd.ExecuteReader();

dr.Close();
}
else if (txtDate.Text != "")
{
SqlCommand cmd = new SqlCommand("SELECT * from book WHERE dateofpurchase = '" + txtDate.Text.ToString());

SqlDataReader dr;
dr = cmd.ExecuteReader();

dr.Close();
}


myConn.Close();


}
}
}

You are more or less the right way.
A problem i can see in your code is in the line:

SqlCommand cmd = new SqlCommand("SELECT * from book WHERE dateofpurchase = '" + txtDate.Text.ToString());

It needs to be only ", and not '";

And after you have done:

SqlDataReader dr;
dr = cmd.ExecuteReader();

You need to read the data so use

dr.Read();

To read what you set above

Now what more help do you need, have you tried to run this code?,
is it working?, do you get what you want?

Wrap up source code with BB code tags.

Read this sample:

DateTime dt;
            // if date is invalid DateTime.MinValue will be assigned to dt
            DateTime.TryParse(textBox1.Text, out dt);
            string q = "";
            if (dt == DateTime.MinValue)
            {
                q = "select * from table1 where name like '" + textBox1.Text + "%'";
            }
            else
            {
                q = "select * from table1 where mydate='" + textBox1.Text + "'";
            }

serkan sendur offcourse it vulnerable to sql injection,
but i dont know if you noticed above is a beginner to c#,
and as it seems he is a beginner in programing as well, so we are not dealing with vulnerabilty here, he simply wants to start to learn.

i want show my result of search in a datagridview. i just want selected title o date i key in show there.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;

namespace WindowsFormsApplication7
{
    public partial class Form7 : Form
    {
        public Form7()
        {
            InitializeComponent();
        }

        private void BindDataGrid()
        {
            SqlConnection myConn = new SqlConnection();
            myConn.ConnectionString = ConfigurationManager.ConnectionStrings["myConn"].ToString();

            myConn.Open();


            string strSQL = "select * from book where user_id = " + StaticData.ActiveUserId + "";
            SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, myConn);
            SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

            SqlCommand cmd = new SqlCommand("select user_id from book where user_id = " + StaticData.ActiveUserId + "", myConn);

            DataTable table = new DataTable();
            dataAdapter.Fill(table);
            bindingSource1.DataSource = table;
            dataGridView1.DataSource = bindingSource1;

            myConn.Close();
        }



        private void button1_Click(object sender, EventArgs e)
        {

            SqlConnection myConn = new SqlConnection();
            myConn.ConnectionString = ConfigurationManager.ConnectionStrings["myConn"].ToString();

            myConn.Open();

          if (txtTitle.Text != "")
           {

               SqlCommand cmd = new SqlCommand("SELECT * from book WHERE title = " + txtTitle.Text.ToString());

               SqlDataReader dr;
               dr = cmd.ExecuteReader();

                 BindDataGrid();

               dr.Close();
            }
          else if (txtDate.Text != "")
           {
              SqlCommand cmd = new SqlCommand("SELECT * from book WHERE dateofpurchase = " + txtDate.Text.ToString());

               SqlDataReader dr;
            dr = cmd.ExecuteReader();

              dr.Close();
           }


            myConn.Close();




        }
    }
}

Edited 3 Years Ago by Reverend Jim: Fixed formatting

Comments
use code tags

you should add the parameters like below :

using System;        
using System.Drawing;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;

public class MainClass
{
  [STAThread]
  static void Main() 
  {
    string cstr = "server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;";
    using ( SqlConnection conn = new SqlConnection( cstr ) )
    {
      conn.Open();

      string selstr = "select FirstName from Employee where lastname = @name";
      SqlCommand cmd = new SqlCommand( selstr, conn );
      SqlParameter name = cmd.Parameters.Add( "@name", SqlDbType.NVarChar, 15 );
      name.Value = "Tang";
      SqlDataReader rdr = cmd.ExecuteReader();

      if ( rdr.Read() )
      {
        Console.WriteLine(rdr.GetString( 0 ) );
      }
      else
      {
        Console.WriteLine("not available yet" );
      }
    }

  }
}

"Tang" will be your textbox.text.

serkan sendur offcourse it vulnerable to sql injection,
but i dont know if you noticed above is a beginner to c#,
and as it seems he is a beginner in programing as well, so we are not dealing with vulnerabilty here, he simply wants to start to learn.

i posted an example as how to create parameters in secure way. this way it will be protected against injection.

dummy c# you are now using two different methods of polling the data from the DB, either you want to use DataBind or you want to use SqlDataReader, choose one and we will continue from there.

and you have not still added the:

dr.Read()

Method

i posted an example as how to create parameters in secure way. this way it will be protected against injection.

WOW you are so centered in your self that you quote me and tell me sonthing else, I KNOW HOW TO DO IT IN A SECURE WAY, BUT ITS NOT THE ISSUE...!!!

what were you expecting ? am i going to be "you" centered, of course i am self-centered.
if you teach someone something, why not teach it correct from the beginning?

Becuase when you teach a baby to talk you are not teaching him how to say "encyclopedia" from the begining you teaching him how to say "dad", "mom" and so on, when he learned that so you going and teach him how to say "cow", "cat" and after you teach him to say "encyclopedia".

I'm sure when you started to learn programing you didnt learn how to id in a secure way from the begining you learned the basicics and then you developed to what you know today, so take it easy with the fellow

Comments
Good point. I can understand your anger, don't let it become a priority. Your English suffers from it.

I dont think so, even in the microsoft websites beginning tutorials for novices, it teaches how to do it proper way from the beginning. Using one more object is better than making quotation mistakes in a select statement as well as security issue.

Well obviously you are not a perent and not a teacher either.
If you still think that you are right so stay in your mind, I cant force you to change the way you think, but I'm sure that people here will agree with me.

Comments
Don't offend. I am not agree with you.

Serkan Sendur I'm done argueing with you, stay in your mind.
To the issue that this thread opended from the begining:
dummy C# have you successfully implanted the code and its working or you need more help?

i dont know what is your first language but i like this expression "stay in your mind" and i will use it from now on( i dont remember having heard of it before).

please dun argue bcoz of teaching me this noobie. T_T
if i choose to use DataBind method. Is this the right code?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;



namespace WindowsFormsApplication7
{
    public partial class Form7 : Form
    {
        public Form7()
        {
            InitializeComponent();
        }

        private void BindDataGrid()
        {
            SqlConnection myConn = new SqlConnection();
            myConn.ConnectionString = ConfigurationManager.ConnectionStrings["myConn"].ToString();

            myConn.Open();
            if (txtTitle.Text != "")
            {

                string strSQL = "select * from book where user_id = " + StaticData.ActiveUserId + " and title = '" + txtTitle.Text + "'";
                SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, myConn);
                SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

                SqlCommand cmd = new SqlCommand("select user_id from book where user_id = " + StaticData.ActiveUserId + "", myConn);

                DataTable table = new DataTable();
                dataAdapter.Fill(table);
                bindingSource1.DataSource = table;
                dataGridView1.DataSource = bindingSource1;
            }
            else if (txtDate.Text != "")
            {
                string strSQL = "select * from book where user_id = " + StaticData.ActiveUserId + " and dateofpurchase = '" + txtDate.Text + "'";
                SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, myConn);
                SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

                SqlCommand cmd = new SqlCommand("select user_id from book where user_id = " + StaticData.ActiveUserId + "", myConn);

                DataTable table = new DataTable();
                dataAdapter.Fill(table);
                bindingSource1.DataSource = table;
                dataGridView1.DataSource = bindingSource1;
            }

            myConn.Close();
        }



        private void button1_Click(object sender, EventArgs e)
        {
            BindDataGrid();

        }
    }
}

Edited 3 Years Ago by Reverend Jim: Fixed formatting

Try:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;



namespace WindowsFormsApplication7
{
    public partial class Form7 : Form
    {
        public Form7()
        {
            InitializeComponent();
        }

        private void BindDataGrid(string strSQL)
        {
            SqlConnection myConn = new SqlConnection();
            myConn.ConnectionString = ConfigurationManager.ConnectionStrings["myConn"].ToString();

            SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, myConn);
            SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

            DataTable table = new DataTable();
            dataAdapter.Fill(table);
            bindingSource1.DataSource = table;
            dataGridView1.DataSource = bindingSource1;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string strSQL = "select * from book where user_id = " + StaticData.ActiveUserId + " and title = '" + txtTitle.Text + "'";
            BindDataGrid(strSQL);
        }
        private void button2_Click(object sender, EventArgs e)
        {
            string strSQL = "select * from book where user_id = " + StaticData.ActiveUserId + " and dateofpurchase = '" + txtDate.Text + "'";
            BindDataGrid(strSQL);
        }
    }
}

its more readable;

thx idanS i understand u do it more simple for me to understand the code but i just want 1 button only for search for both title and date.
1st condition i key in title with empty date textbox, i get correct thing.
2nd condtion i key in title with empty date textbox, i get correct thing.
but when 3rd condition i key in both title n date textbox , i juz get the result of search same like the title but not same with the date.
what should i do? can u get it what i mean?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;



namespace WindowsFormsApplication7
{
    public partial class Form7 : Form
    {
        public Form7()
        {
            InitializeComponent();
        }

        private void BindDataGrid()
        {
            SqlConnection myConn = new SqlConnection();
            myConn.ConnectionString = ConfigurationManager.ConnectionStrings["myConn"].ToString();

            myConn.Open();

             if (txtTitle.Text != "")
              {
                string strSQL = "select * from book where user_id = " + StaticData.ActiveUserId + " and title = '" + txtTitle.Text + "'";
                SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, myConn);
                SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

                SqlCommand cmd = new SqlCommand("select user_id from book where user_id = " + StaticData.ActiveUserId + "", myConn);

                DataTable table = new DataTable();
                dataAdapter.Fill(table);
                bindingSource1.DataSource = table;
                dataGridView1.DataSource = bindingSource1;
              }

             else if  (txtDate.Text != "")
              {
                  string strSQL = "select * from book where user_id = " + StaticData.ActiveUserId + " and dateofpurchase = '" + txtDate.Text + "'";
                  SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, myConn);
                  SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

                  SqlCommand cmd = new SqlCommand("select user_id from book where user_id = " + StaticData.ActiveUserId + "", myConn);

                  DataTable table = new DataTable();
                  dataAdapter.Fill(table);
                  bindingSource1.DataSource = table;
                  dataGridView1.DataSource = bindingSource1;

              }
      [COLOR="Red"]problem is here[/COLOR]       else if (txtTitle.Text != "" && txtDate.Text != "")
             {
                 string strSQL = "select * from book where user_id = " + StaticData.ActiveUserId + " ,title = '" + txtTitle.Text + "'and dateofpurchase = '" + txtDate.Text + "'";
                 SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, myConn);
                 SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

                 SqlCommand cmd = new SqlCommand("select user_id from book where user_id = " + StaticData.ActiveUserId + "", myConn);

                 DataTable table = new DataTable();
                 dataAdapter.Fill(table);
                 bindingSource1.DataSource = table;
                 dataGridView1.DataSource = bindingSource1; 
             }

             else if (txtTitle.Text == "" && txtDate.Text == "")
             {
                 MessageBox.Show("Please key in the information");
             }


            myConn.Close();
        }



        private void button1_Click(object sender, EventArgs e)
        {

            BindDataGrid();
       }
    }
}

Edited 3 Years Ago by Reverend Jim: Fixed formatting

Hi dummy C#,

Of course when you enter in both of the text boxs values and press this button it will give the result like you have entered only in the first button, because look how you build your if statment...!
first you ask:

if (txtTitle.Text != "")

then you ask:

else if (txtDate.Text != "")

and only then you ask:

else if (txtTitle.Text != "" && txtDate.Text != "")

What im tring to say is, in IF statment the first thing that is true is happning. so in your first if you ask:

if (txtTitle.Text != "")

so of course it will do this block and will not run to the next one.
what you can do its two things:
1. change your code that the last block will be the first like this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;



namespace WindowsFormsApplication7
{
public partial class Form7 : Form
{
public Form7()
{
InitializeComponent();
}

private void BindDataGrid()
{
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = ConfigurationManager.ConnectionStrings["myConn"].ToString();

myConn.Open();

if (txtTitle.Text != "" && txtDate.Text != "")
{
string strSQL = "select * from book where user_id = " + StaticData.ActiveUserId + " ,title = '" + txtTitle.Text + "'and dateofpurchase = '" + txtDate.Text + "'";
SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, myConn);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

SqlCommand cmd = new SqlCommand("select user_id from book where user_id = " + StaticData.ActiveUserId + "", myConn);

DataTable table = new DataTable();
dataAdapter.Fill(table);
bindingSource1.DataSource = table;
dataGridView1.DataSource = bindingSource1; 
}
else if (txtTitle.Text != "")
{
string strSQL = "select * from book where user_id = " + StaticData.ActiveUserId + " and title = '" + txtTitle.Text + "'";
SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, myConn);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

SqlCommand cmd = new SqlCommand("select user_id from book where user_id = " + StaticData.ActiveUserId + "", myConn);

DataTable table = new DataTable();
dataAdapter.Fill(table);
bindingSource1.DataSource = table;
dataGridView1.DataSource = bindingSource1;
}

else if (txtDate.Text != "")
{
string strSQL = "select * from book where user_id = " + StaticData.ActiveUserId + " and dateofpurchase = '" + txtDate.Text + "'";
SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, myConn);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

SqlCommand cmd = new SqlCommand("select user_id from book where user_id = " + StaticData.ActiveUserId + "", myConn);

DataTable table = new DataTable();
dataAdapter.Fill(table);
bindingSource1.DataSource = table;
dataGridView1.DataSource = bindingSource1;

}



myConn.Close();
}

2. or you can use the switch statment.

This article has been dead for over six months. Start a new discussion instead.