Fill DropDownList from database - c#

I am new to C# and trying to populate a DropDownList based on a database value. I tried connecting to database as shown below - tested with the statement and it says connected. Can I assume this is correct? Am I on the right track? Also, how do I then select value from the table and fill DropDownList with a field?
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection (
"Data Source=.\\SQLEXPRESS;AttachDbFilename=C:customers.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
try
{
connection.Open();
TextBox1.Text = "connected";
}
catch (Exception)
{
TextBox1.Text = " not connected";
}
}

protected void Page_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection (
"Data Source=.\\SQLEXPRESS;AttachDbFilename=C:customers.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
try
{
SqlDataReader dReader;
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
cmd.CommandText ="Select distinct [Name] from [Names]" +
" order by [Name] asc";
connection.Open();
dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)
{
while (dReader.Read())
//Names collection is a combo box.
namesCollection.Add(dReader["Name"].ToString());
}
else
{
MessageBox.Show("Data not found");
}
dReader.Close()
TextBox1.Text = "connected";
}
catch (Exception)
{
TextBox1.Text = " not connected";
}
}
Hope that helps................

It's So Much Simple :----
SqlConnection con = new SqlConnection();
DataSet ds = new DataSet();
con.ConnectionString = #"Data Source=TOP7\SQLEXPRESS;Initial Catalog=t1;Persist Security Info=True;User ID=Test;Password=t123";
string query = "Select * from tbl_User";
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandText = query;
con.Open();
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
adpt.Fill(ds);
comboBox1.Items.Clear();
comboBox1.DisplayMember = "UserName";
comboBox1.ValueMember = "UserId";
comboBox1.DataSource = ds.Tables[0];
------------------------------------------------------------------------

using (SqlConnection con = new SqlConnection("Data Source = NIPOON; Initial Catalog = CustomerOrders; Integrated Security = true"))
{
SqlCommand cmd = new SqlCommand("SELECT Name FROM Customer", con);
con.Open();
dropDownList.DataSource = cmd.ExecuteReader();
dropDownList.DataTextField = "Name";
dropDownList.DataValueField = "Name";
dropDownList.DataBind();
}

Related

About C# in ASP.NET and SQL Server

I have a drop down list that binding data from database table and I can show it, but when I wanna show the data when I selected the drop down list value, it can't show anything
Here is my code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.DataSource = GetData();
DropDownList1.DataTextField = "DEPT_NAME";
DropDownList1.DataValueField = "DEPT_NO";
DropDownList1.DataBind();
}
}
protected void dropdownlist1_SelectedIndexChanged(object sender, EventArgs e)
{
string value = DropDownList1.SelectedValue;
using (SqlConnection conn = new SqlConnection(#"Data Source=server;Initial Catalog=DB;User ID=id;Password=pw"))
{
using (SqlCommand cmd = new SqlCommand("SELECT TEL_NO,EMP_NAME,EMP_POSITION FROM tel WHERE DEPT_NO =" +value, conn))
{
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
this.GridView1.Visible = true;
GridView1.DataSource = dr;
GridView1.DataBind();
dr.Close();
conn.Close();
}
}
}
DataTable GetData()
{
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(#"Data Source=server;Initial Catalog=DB;User ID=id;Password=pw"))
{
using (SqlCommand cmd = new SqlCommand("SELECT 'Please Select' AS DEPT_NAME , '000' AS DEPT_NO UNION SELECT DEPT_NAME , DEPT_NO FROM dept ORDER BY DEPT_NO ASC", conn))
{
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
}
}
return dt;
}
using (SqlCommand cmd = new SqlCommand("SELECT TEL_NO,EMP_NAME,EMP_POSITION FROM tel WHERE DEPT_NO = #value", conn))
cmd.Parameter.AddWithValue("#value",value);
Query ( "SELECT TEL_NO,EMP_NAME,EMP_POSITION FROM tel WHERE DEPT_NO =" +value) will work if DEPT_NO dataType is number

How to display SQL search results in a datagrid using WPF

private void Button_Click(object sender, RoutedEventArgs e)
{
SqlConnection sc = new SqlConnection();
SqlCommand com = new SqlCommand();
sc.Open();
com.Connection = sc;
string sql;
{
sql = "SELECT FROM WolfAcademyForm WHERE [Forename] == 'txtSearch.Text';";
{
grdSearch.ItemsSource = sql;
sc.Close();
}
This is the code that I have, When I press the search button nothing shows up... Can someone please help me with this problem, I don't get any errors
Problems:
SQL query is not right:
It should be like SELECT * FROM TABLENAME.
In WHERE clause [Forename] == 'txtSearch.Text', == should = and Textbox value should be concatenated using +.
Fixed Code:
private void Button_Click(object sender, RoutedEventArgs e)
{
string sConn = #"Data Source=MYDS;Initial Catalog=MyCat;
User ID=MyUser;Password=MyPass;";
using(SqlConnection sc = new SqlConnection(sConn))
{
sc.Open();
string sql = "SELECT * FROM WolfAcademyForm WHERE [Forename]= #Forename";
SqlCommand com = new SqlCommand(sql, sc);
com.Parameters.AddWithValue("#Forename", txtSearch.Text);
using(SqlDataAdapter adapter = new SqlDataAdapter(com))
{
DataTable dt = new DataTable();
adapter.Fill(dt);
grdSearch.ItemsSource = dt.DefaultView;
}
}
}
Use this
using (SqlConnection con = new SqlConnection(ConString))
{
CmdString = "SELECT FROM WolfAcademyForm WHERE [Forename] == " + txtSearch.Text + ";"
SqlCommand cmd = new SqlCommand(CmdString, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("Employee");
sda.Fill(dt);
grdSearch.ItemsSource = dt.DefaultView;
}

How to populate a DataGridView by selecting any table from combo box

I have used the following code for displaying names of my SQL db tables in a combo box.
Now I want that when I click on any of these table names from the combo box, my DGV populates with that table's contents.
private void Form1_Load(object sender, EventArgs e)
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select table_name from information_schema.tables";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
comboBox1.DataSource = dtRecord;
comboBox1.DisplayMember = "TABLE_NAME";
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Then I used the following code for populating my DGV but it's not working; please help.
private void PopulateGridView()
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strconnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "select * from " + comboBox1.SelectedText;
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dtRecord;
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedValue != null)
{
PopulateGridView(comboBox1.SelectedValue.ToString());
}
}
just try this:
update your code in the Form Load with below:
private void Form1_Load(object sender, EventArgs e)
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select table_name from information_schema.tables";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
comboBox1.DataSource = dtRecord;
comboBox1.DisplayMember = "table_name";
comboBox1.ValueMember = "table_name";
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
so basically you have added one extra line comboBox1.ValueMember = "table_name";
and make your PopulateGridView method like this:
private void PopulateGridView(string tblName)
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "select * from " + tblName;
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dtRecord;
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
it has to work.
Also, I see, you are creating SqlConnection object everywhere, including SqlCommand and SqlDataAdapter.
try to wrap them up in static methods i.e.
- public static SqlConnection OpenConnection()
- public static DataTable ExecuteSelectQuery(string Query)
- public static bool ExecuteModifyQuery(string Query)
try to write as less amount of code as you can.
Try this:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedValue != null)
{
string strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strconnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "select * from " + comboBox1.SelectedValue;
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dtRecord;
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}

inserting textbox value to sql server using c#

I need to add a text box value to SQL Server database table. Below is my code:
private void button1_Click(object sender, EventArgs e)
{
string str = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\timetablesystem.mdf;Integrated Security=True;User Instance=True";
SqlConnection con = new SqlConnection(str);
string qry = "insert into SubjectMaster (SubjectName) values (#TxtSubjectName)";
con.Open();
SqlCommand cmd = new SqlCommand(qry, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#TxtSubjectName", TxtSubjectName.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Added Successfully!!");
con.Close();
}
But, data should not add in table... please help me...
thanks for ur help...
Try debugging your query first if it works i think your connection with your db isnt working.
string str = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\timetablesystem.mdf;Integrated Security=True;User Instance=True";
is there supposed to be this '.' after data source Data Source=.\\SQLEXPRESS
try this and tell me what is the message information content
private void button1_Click(object sender, EventArgs e)
{
string str = "Server=.\SQLEXPRESS;Database=TestDB;Trusted_Connection=True;";
using( SqlConnection con = new SqlConnection(str)){
try{
con.Open();
string qry = "insert into SubjectMaster (SubjectName) values (#TxtSubjectName)";
SqlCommand cmd = new SqlCommand(qry, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#TxtSubjectName", TxtSubjectName.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Added Successfully!!");
}
catch{
MessageBox.Show("connection is failed!!");
}
}
}
try this
SqlConnection con = new SqlConnection(#"Data Source=SL-20\SQLEXPRESS;Initial Catalog=TestDB;User ID=sa;Password=sl123;");
string query = " insert into name(name)values('" + TextboxTest.Text + "')";
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();

Search engine by Drop Down List selection and text box entry searches Database for the entry and displays in aspx

I am trying to create a search from ProductDB(database), the main columns I would like the user to search is Material_No and Product_Line.
So far, I have the following:
Drop Down List:
<asp:DropDownList ID="DropDownList" runat="server" Height="16px"
onclick="SearchButton_Click" Width="144px"
AutoPostBack="True">
<asp:ListItem>Please select...</asp:ListItem>
<asp:ListItem Value="0">Material No</asp:ListItem>
<asp:ListItem Value="1">Product Line</asp:ListItem>
</asp:DropDownList>
TextBox:
<asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged">
</asp:TextBox>
Search Button:
<asp:Button ID="SearchButton" runat="server" Text="Search"
onclick="SearchButton_Click" />
So I am trying to do is when the user chooses either Material No or Product Line when he types the Material No or Product Line after clicking the search button, the result should show either in grid format or something similar, and if he just clicks search without choosing anything all the result should show.
Here is what I have done so far.
Old Code:
protected void SearchButton_Click(object sender, EventArgs e)
{
string Selectedvalue = DropDownList.SelectedItem.Value;
if (DropDownList.SelectedItem.ToString() == "Material No")
{
MessageBox.Show("Material No selected");
string textbox = TextBox1.Text;
MessageBox.Show(textbox.ToString());
SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=ROG;Integrated Security=True");
DataSet dsData = new DataSet();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM ProductDB WHERE Material_No ='" + TextBox1.Text + "'";
cmd.Connection = conn;
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("", conn);
SqlCommandBuilder cmdBldr = new SqlCommandBuilder(da);
da.Fill(dsData, TextBox1.Text);
MessageBox.Show("Connection Successful");
conn.Close();
}
else
{
MessageBox.Show("Product Line selected");
}
}
New Code:
private SqlConnection conn;
private SqlDataAdapter daMaterial;
private SqlDataAdapter daProduct;
private SqlCommand cmdMaterial;
private SqlCommand cmdProduct;
private SqlParameter paramMaterial;
private SqlParameter paramProduct;
private DataSet dsMaterial;
private DataSet dsProduct;
private DataGrid dgMaterial;
private DataGrid dgProduct;
private const string tableNameMaterial = "Material_No";
private const string tableNameProduct = "Product_Line";
enter code here
protected void SearchButton_Click(object sender, EventArgs e)
{
string Selectedvalue = DropDownList.SelectedItem.Value;
if (DropDownList.SelectedItem.ToString() == "Material No")
{
//MessageBox.Show("Material No. Selected");
string textbox = TextBox1.Text;
//MessageBox.Show(textbox.ToString());
conn = new SqlConnection("Data Source=localhost;Initial Catalog=ROG;Integrated Security=True");
dsMaterial = new DataSet();
daMaterial = new SqlDataAdapter("SELECT * FROM ProductDB WHERE Material_No = #Material_No", conn);
daMaterial.SelectCommand.CommandText = "SELECT * FROM ProductDB WHERE Material_No = #Material_No";
paramMaterial = new SqlParameter();
paramMaterial.ParameterName = "#Material_No";
paramMaterial.Value = TextBox1.Text;
daMaterial.SelectCommand = cmdMaterial;
cmdMaterial.Parameters.Add("#Material_No", SqlDbType.BigInt).Value = TextBox1.Text;
daMaterial.Fill(dsMaterial, tableNameMaterial);
//MessageBox.Show("Connection Successful");
conn.Close();
}
else
{
//MessageBox.Show("Product Line selected");
string textbox = TextBox1.Text;
//MessageBox.Show(textbox.ToString());
conn = new SqlConnection("Data Source=localhost;Initial Catalog=ROG;Integrated Security=True");
dsProduct = new DataSet();
daProduct = new SqlDataAdapter("SELECT * FROM ProductDB WHERE Product_Line = #Product_Line", conn);
daProduct.SelectCommand.CommandText = "SELECT * FROM ProductDB WHERE Product_Line = #Product_Line";
paramProduct = new SqlParameter();
paramProduct.ParameterName = "#Product_Line";
paramProduct.Value = TextBox1.Text;
daProduct.SelectCommand = cmdProduct;
cmdProduct.Parameters.Add("#Product_Line", SqlDbType.VarChar, 50).Value = TextBox1.Text;
conn.Open();
daProduct.Fill(dsProduct, tableNameProduct);
//MessageBox.Show("Connection Successful");
conn.Close();
}
}
I am getting an error "Object reference not set to an instance of an object."
Can someone check whether the Parameter use is correct with the SqlDataAdapter
protected void btnSearch_Click(object sender, EventArgs e)
{
string Query = string.Empty;
try
{
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
if (DropDownList1.SelectedValue.ToString() == "Name")
{
Query = "select * from tbl_Employee where Name Like '" + txtSearchName.Text + "%'";
}
else if (DropDownList1.SelectedValue.ToString() == "Designation")
{
Query = "select * from tbl_Employee where Designation Like '" + txtSearchName.Text + "%'";
}
SqlDataAdapter sqlDa = new SqlDataAdapter(Query, sqlCon);
DataSet Ds = new DataSet();
sqlDa.Fill(Ds);
dgvEmployee.DataSource = Ds;
dgvEmployee.DataBind();
}
catch (Exception ex)
{
HttpContext.Current.Response.Write("<script>alert('wfrmGrid: 11')</script>" + ex.Message);
}
}
Some things:
daProduct = new SqlDataAdapter("SELECT * FROM ProductDB WHERE Product_Line = #Product_Line", conn);
Creates a new SqlDataAdapter and initializes it's SelectCommand with the CommandText and Connection, hence following lines are redundant and inherently error-prone:
daProduct.SelectCommand.CommandText = "SELECT * FROM ProductDB WHERE Product_Line = #Product_Line";
daProduct.SelectCommand = cmdProduct;
The second instruction even overrides the first with a new CommandText and Connection without ever having used.
paramProduct = new SqlParameter();
Instead of using this parameterless constructor i would use AddWithValue or Parameters.Add which are less error-prone(e.g. you haven't provide a type).
cmdProduct.Parameters.Add( ....
Now you are using the method i've suggested without ever having used paramProduct.
You're also never disposing unmanaged resources(e.g. connections are staying open in case of errors), use the using-statement therefore. Btw, if you use a DataAdapter you don't even need to open/close the connection, that is done implicitely on DataAdapter.Fill.
Sorry, but your code is a mess.Instead of fiddling around with yours, i'll provide a clean version that should work.
....
else
{
using(var con = new SqlConnection("Data Source=localhost;Initial Catalog=ROG;Integrated Security=True"))
using (var daProduct = new SqlDataAdapter("SELECT * FROM ProductDB WHERE Product_Line = #Product_Line", con))
{
daProduct.SelectCommand.Parameters.Add("#Product_Line", SqlDbType.VarChar, 50).Value = TextBox1.Text;
dsProduct = new DataSet();
daProduct.Fill(dsProduct, "Product_Line");
}
}
The following code is working:
private const string tableNameMaterial = "Material_No";
private const string tableNameProduct = "Product_Line";
protected void SearchButton_Click(object sender, EventArgs e)
{
string Selectedvalue = DropDownList.SelectedItem.Value;
if (DropDownList.SelectedItem.ToString() == "Material No")
{
//MessageBox.Show("Material No. Selected");
string textbox = TextBox1.Text;
//MessageBox.Show(textbox.ToString());
SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=ROG;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM ProductDB WHERE Material_No = #Material_No";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#Material_No", SqlDbType.BigInt);
cmd.Parameters["#Material_No"].Value = TextBox1.Text;
SqlDataAdapter daMaterial = new SqlDataAdapter();
daMaterial.SelectCommand = cmd;
DataSet dsMaterial = new DataSet();
conn.Open();
daMaterial.Fill(dsMaterial, tableNameMaterial);
//MessageBox.Show("Connection Successful");
GridView1.DataSource = dsMaterial;
GridView1.DataBind();
conn.Close();
}
else
{
//MessageBox.Show("Product Line selected");
string textbox = TextBox1.Text;
//MessageBox.Show(textbox.ToString());
SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=ROG;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM ProductDB WHERE Product_Line = #Product_Line";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#Product_Line", SqlDbType.VarChar);
cmd.Parameters["#Product_Line"].Value = TextBox1.Text;
SqlDataAdapter daProduct = new SqlDataAdapter();
daProduct.SelectCommand = cmd;
DataSet dsProduct = new DataSet();
conn.Open();
daProduct.Fill(dsProduct, tableNameProduct);
//MessageBox.Show("Connection Successful");
GridView1.DataSource = dsProduct;
GridView1.DataBind();
conn.Close();
}
}
Now, I need the search box to autocomplete the letters from the database... if anyone has any suggestion, please do share it.
Thank you

Categories