Search in Database, output in DataGridView - c#

I have a Database with 2 Tables. Now i want to search for Values in my Databases.
I use this GUI so the "User" can give Information to the Textbox and the searched Values should shown in my Datagridview
I use this Code:
private void TB_MSGHeadline_TextChanged(object sender, EventArgs e)
{
try
{
if (TB_MSGHeadline.Text.Equals(""))
{
}
else
{
DataView dv = new DataView(table);
dv.RowFilter = string.Format("MessageHeadline LIKE '%{0}%'", TB_MSGHeadline.Text);
dataGridView1.DataSource = dv;
}
}
catch (Exception i)
{
MessageBox.Show("" + i);
}
}
Fill the DataGridview
private void GetData(string selectCommand)
{
//Creating a new data adapter based on the specified query.
dataAdapter = new SqlDataAdapter(selectCommand, ConnectionString);
//Create a command builder to generate SQL update, insert, and
//delete commands based on selectCommand. These are used to
//update the Database.
SqlCommandBuilder CommandBuilder = new SqlCommandBuilder();
//Populate a new data table and bind it to the BindingSource
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
BindingSource1.DataSource = table;
}
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = BindingSource1;
GetData("SELECT * FROM Tabelle1");
}
(Found it in a video but dont work for my problem)
But i get the Error, that the row "MessageHeadline" wasnt found
So i want to know, how can i make a LIKE search for my SQL Database?

Related

How to query a dataset in C# and return the results to a datagridview?

I have datagridview which displays it's data source (SQL database for an inventory system).
What I would like to be able to do is filter what is shown in the datagridview based on if something has been ordered etc...
So I am filling the datagridview like this:
private void Form1_Load(object sender, EventArgs e)
{
bG_T1TableAdapter.Fill(bUZZGEEF_DBDataSet.BG_T1);
ResizeCols();
}
but I can't for the life of me figure out how to query the dataset.
For instance I would like to click a button and that would display all rows in which the ordered column has been checked.
But in general I would like to know how to build my own queries.
You can use a DataView for the above purpose and bind the filtered DataView to the DataGrid.
bG_T1TableAdapter.Fill(bUZZGEEF_DBDataSet.BG_T1);
DataView dv = new DataView(bUZZGEEF_DBDataSet.BG_T1);
dv.RowFilter = "query"; // query example = "id = 10"
myDataGridView.DataSource =dv;
For more information, You can look here
You can use the DataTableView RowFilter to query a datatable
bG_T1TableAdapter.Fill(bUZZGEEF_DBDataSet.BG_T1);
bUZZGEEF_DBDataSet.BG_T1.DefaultView.RowFilter = "ID < 10";
myDataGridView.DataSource =bUZZGEEF_DBDataSet.BG_T1.DefaultView;
https://msdn.microsoft.com/en-us/library/system.data.dataview.rowfilter(v=vs.110).aspx
I think you want something like what you see in the code sample below. Basically, start typing in the TextBox, and the results in the GridView will be filtered, relative to what is entered into the TextBox.
using System.Data.SqlClient;
public class Form1
{
DataSet ds = new DataSet;
private void Form1_Load(System.Object sender, System.EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=name_of_your_sql_server; Integrated Security=true; Initial Catalog=name_of_your_database");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Categories", con);
da.Fill(ds, "Cat");
DataGridView1.DataSource = ds.Tables("Cat");
}
private void TextBox1_TextChanged(System.Object sender, System.EventArgs e)
{
ds.Tables("Cat").DefaultView.RowFilter = "[CategoryName] LIKE '*" + TextBox1.Text + "*'";
}
}

DataGridView CheckBox Column - Show CheckBox but store String

Here is my code :
public partial class Form1 : Form
{
SqlCommandBuilder cmbl;
string con = "Data Source=localhost;Initial Catalog=db;Persist Security Info=True;User ID=sa;Password=1234";
SqlDataAdapter sdaHFP;
string QueryDgvHFP = "SELECT * FROM HFP";
DataTable dtHFP;
SqlConnection cn;
public Form1()
{
InitializeComponent();
}
private void Form1(object sender, EventArgs e)
{
sdaHFP = new SqlDataAdapter(QueryDgvHFP, con);
dtHFP = new DataTable();
sdaHFP.Fill(dtHFP);
foreach (DataRow item in dtHFP.Rows)
{
int n = dgvHFP.Rows.Add();
dgvHFP.Rows[n].Cells[0].Value = item["HFP"].ToString();
dgvHFP.Rows[n].Cells[1].Value = item["YearPeriod"].ToString();
if (item["Active"].ToString() == "Y")
{
dgvHFP.Rows[n].Cells[2].Value = true;
}
else
{
dgvHFP.Rows[n].Cells[2].Value = false;
};
dgvHFP.Rows[n].Cells[3].Value = item["ID"].ToString();
}
}
That's was load data from Sql Query to DataGridView, And I was add a Button for execute update or insert within this code :
private void btUpdate_Click(object sender, EventArgs e)
{
try
{
cmbl = new SqlCommandBuilder(sdaHFP);
sdaHFP.Update(dtHFP);
MessageBox.Show("Success", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
When I Update / Insert data in DataGridView and click that Update Button, a Success MessageBox appears, but the Data in Database not Updated nor Inserted
Please help me solve this problem, why the Update Button doesn't work?
Thank You Very Much.
You should bind the DataGridView to DataTable, then when you change a cell value or add or remove rows, the changes apply on DataTable. Then you can save data table changes using a TableAdapter:
this.dataGridView1.DataSource = dataTable;
Note: To store true/false or Yes/No values, it's better to use bit data type in sql server. But in the below example I supposed you need to store values as Y/N as nvarchar(50) and I setup a DataGridViewCheckBoxColumn to support editing a string column.
Example
Suppose we have a table Table1:
Column1: int, primary key
Column2: nvarchar(50), Allows Null, Containing Y or N as vaule
And we want to edit data of Table1 in a DataGridView:
Here is the code you can use to load and edit and save data:
private DataTable table;
private SqlDataAdapter dataAdapter;
private void sampleForm_Load(object sender, EventArgs e)
{
var command = "SELECT * FROM Table1";
var connection = #"Your connection string";
table = new DataTable();
dataAdapter = new SqlDataAdapter(command, connection);
var commandBuilder = new SqlCommandBuilder(dataAdapter);
dataAdapter.Fill(table);
//Set false as default value for Column2
table.Columns["Column2"].DefaultValue = false;
var column1 = new DataGridViewTextBoxColumn();
column1.Name = "Column1";
column1.DataPropertyName = "Column1";
var column2 = new DataGridViewCheckBoxColumn();
column2.Name = "Column2";
column2.DataPropertyName = "Column2";
column2.TrueValue = "Y";
column2.FalseValue = "N";
this.dataGridView1.Columns.Add(column1);
this.dataGridView1.Columns.Add(column2);
//Bind grid to table
this.dataGridView1.DataSource = table;
}
private void saveButton_Click(object sender, EventArgs e)
{
//Save data
this.dataGridView1.EndEdit();
dataAdapter.Update(table);
}

Update gridview content on textbox_TextChanged event outside the gridview

I have searched for this but could not find any solution for textchanged event outside the gridview causing changes in results. I am unable to attach image being a newbie. I want results shown in gridview through data table to update according to what I type in textbox placed outside of gridview. code in c# will be appreciated. In the end, I want to retrieve ID on pressing ENTER key to use further.
private void textBox1_TextChanged(object sender, EventArgs e)
{
DataTable table = new DataTable();
string sql; table.Columns.Add("Name");
dbconnect db = new dbconnect();
db.createconnection();
sql = "select custcompany from customer";
db.dbadapter = new OleDbDataAdapter(sql, db.dbconnection);
DataTable dtt = new DataTable();
db.dbadapter.Fill(dtt);
for (int i = 0; i < dtt.Rows.Count; i++)
{
table.Rows.Add(dtt.Rows[i][0]);
}
sql = "select suppcompany from supplier";
db.dbadapter = new OleDbDataAdapter(sql, db.dbconnection);
DataTable dtt1 = new DataTable();
db.dbadapter.Fill(dtt1);
for (int i = 0; i < dtt1.Rows.Count; i++)
{
table.Rows.Add(dtt1.Rows[i][0]);
}
dataGridView1.DataSource = table;
if (textBox1.Text != "")
{
DataView dv = new DataView();
dv.RowFilter = string.Format("Name = '{0}'", textBox1.Text);
dataGridView1.DataSource = dv;
}
else if (textBox1.Text == "")
{
dataGridView1.DataSource = table;
}
}
table is the name of DataTable populated on Load event.
If test box has value, you are creating a new instance of DataView and assigning it to the dataGridView1, my question is is there value in DataView object? If you are doing exactly what you have given in the question then it won't work, because dv doesn't have value to show in the dataGridView1.
Get the table data on TextChanged event by accessing the database. If you have any code where you are getting the database values into the table then use it in this event before binding to the DataGridView1.
Because the table value will be lost after PostBack. So you need to reload the value into table again. Try the following,
private void textBox1_TextChanged(object sender, EventArgs e)
{
//table = fill the table with proper values by accessing the database
if (textBox1.Text != "")
{
DataView dv = table.DefaultView;
dv.RowFilter = string.Format("Name = '{0}'", textBox1.Text);
dataGridView1.DataSource = dv;
dataGridView1.DataBind();
}
else if (textBox1.Text == "")
{
dataGridView1.DataSource = table;
dataGridView1.DataBind();
}
}
Update
To search names that begins with letters use,
dv.RowFilter = string.Format("Name like '{0}%'", textBox1.Text);
To search names that contains a letters use,
dv.RowFilter = string.Format("Name like '%{0}%'", textBox1.Text);
To search names that ends with letters,
dv.RowFilter = string.Format("Name like '%{0}'", textBox1.Text);

How to show record in DataGridView based on selected ComboBox item?

I am making windows application and am stuck at one place.
My problem is that i want to display record in a DataGridView by selecting a ComboBox item but I do not understand the proper way to do it. Please help me in overcome this problem.
private void grid_Load(object sender, EventArgs e)
{
con = new SqlConnection(constr);
try
{
con.Open();
//this.studTableAdapter.Fill(this.pRJTestDBDataSet.stud);
//above line show error for connection to database
da = new SqlDataAdapter("SELECT stud_no FROM stud", con);
DataTable dt = new DataTable();
da.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "stud_no";
comboBox1.ValueMember = "stud_no";
comboBox1.DataSource = dt;
comboBox1.SelectedIndex = -1;
comboBox1_SelectedIndexChanged(sender, e);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{ con.Close(); }
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
this.studTableAdapter.Fill(pRJTestDBDataSet.stud);
//above line show error for connection to database
}
i have tried above code but its not working there error like login fail to user
cmd = new SqlCommand("SELECT stud_no FROM stud", con);
da = new SqlDataAdapter(cmd);
da.Fill(dt);
Combobox1.DataSource = dt;
Combobox1.DisplayMember = dt.Columns("Stud_no").ToString;
rebind the DataGrid at each SelectedItemIndex change event of Combo Box by the data you want to bind.
private void button2_Click(object sender, EventArgs e)//button 2 is a show data button
{
if (combo_floor.Text != "")
{
DataSet ds = new DataSet();
string sql = "select floor_id,floor_no,floor_remark,floor_entrydate from Floorinfo where floor_no='"+combo_floor.Text+"'";
ds = c.select_query(sql);
dataGridView1.DataSource = ds.Tables["a"];
combo_floor.Text = "";
}
else
{
showdata();
//showdata()is made for show all data from the given table name
}
}
//connection is in different class so please dont mind

Datagrid Binding Question

I am new at this. I am trying to populate a datagrid from a table source. My code is attempting to do two things.
First it populates a dataGrid with columns from a table. Then it adds a column called "SELECT" at the end of the grid. This select is CheckBox. However, when I execute this code, it adds the "SELECT" column twice.
I want to see it once. What am I doing wrong?
private void BankFlow_Load(object sender, EventArgs e)
{
initMethod();
dataTable = getBankFlowData(globalConnection);
dataGridView1.DataSource = dataTable;
}
private static DataTable getBankFlowData(OracleConnection oc)
{
DataTable dt = new System.Data.DataTable();
try
{
OracleCommand od = oc.CreateCommand();
od.CommandText = "SELECT * FROM BANK_FLOW_SOURCE";
od.CommandType = System.Data.CommandType.Text;
OracleDataAdapter adapter = new OracleDataAdapter(od);
adapter.Fill(dt);
}
catch (Exception)
{
}
return dt;
}
private static void initMethod()
{
targetSystem = ConfigurationManager.ConnectionStrings["prototype"].ConnectionString.ToString();
Console.WriteLine("Target : {0}", targetSystem);
sourceSystem = ConfigurationManager.ConnectionStrings["qlprod8"].ConnectionString.ToString();
Console.WriteLine("Source : {0}", sourceSystem);
globalConnection.ConnectionString = sourceSystem;
globalConnection.Open();
}
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
DataGridViewCheckBoxColumn col = new DataGridViewCheckBoxColumn();
col.HeaderText = "SELECT";
col.ReadOnly = false;
col.DefaultCellStyle.BackColor = Color.Beige;
dataGridView1.Columns.Add(col);
}
Your problem is that the databindingcomplete event happens more then you think. In fact anytime some data changes it will fire.
You need to add the column outside of the databindingcomplete event.
EDIT
Actually since you are databinding, you may want to consider adding the column to your datatable. You would do this before the binding the datatable to the grid. Essentially, just create a datacolumn named select, that has the type of boolean and then add the datacolumn to the datatable.

Categories