Adding datarows to datagrid from database - c#

I'm new to databases. I'm trying to make a search utility to match user input string with records in database and display them.
System.Data.SqlClient.SqlConnection con;
System.Data.SqlClient.SqlDataAdapter da;
DataSet ds1;
private void Form1_Load(object sender, EventArgs e)
{
con = new System.Data.SqlClient.SqlConnection();
ds1 = new DataSet();
con.ConnectionString = "";
con.Open();
string sql = "SELECT * From tblLecturers";
da = new System.Data.SqlClient.SqlDataAdapter(sql, con);
da.Fill(ds1, "Lecturers");
con.Close();
}
Form2 secondForm = new Form2();
private void btnFind_Click(object sender, EventArgs e)
{
this.Hide();
secondForm.Show();
string searchFor = textBox1.Text;
int results = 0;
int i;
DataRow[] returnedRows;
if (radioButton1.Checked)
{
returnedRows = ds1.Tables["Lecturers"].Select("Name like '%" + searchFor + "%'");
}
else
{
returnedRows = ds1.Tables["Lecturers"].Select("Department like '%" + searchFor + "%'");
}
results = returnedRows.Length;
if (results > 0)
{
secondForm.dataGridView1.DataSource = returnedRows;
}
else
{
MessageBox.Show("No such Record");
}
}
There's no error but it's just displaying a blank grid. returnedRows contains all the rows whose contents match the user input. I'm pretty sure this isn't though:
secondForm.dataGridView1.DataSource = returnedRows;
Tried rows.add using for loop, won't work. How do i do this?
Thanks in advance.

Call the BindMethod of gridView
if (results > 0)
{
secondForm.dataGridView1.DataSource = returnedRows;
secondForm.dataGridView1.DataBind();
}
else
{
MessageBox.Show("No such Record");
}

Ignore DataBind method, there is no method for windows GridView.
The datarow array can be added to dataset or datatable, using the dataset or datatable we can directly bind the GridView

Related

Whats is proper way of using RowFilter on DataGridView populated with DataTable?

I have followed method from this SO post to perform search on datagridview
Below is my attempt. I would like to stop querying database with DgvSearch() method on text change, instead use RowFilter.
Within current attempt, datagridview is properly populated from LoadDataParts(), when i start typing in TxtPP_GBC2, i see only column header, no exception is thrown.
GBC column is defined as "INT".
Expected result -> TxtPP_GBC2_TextChanged() will behave same like DgvSearch()
public partial class ProgramPart : Form
{
public SqlConnection Con { get; } = new SqlConnection(#"***");
public string UserDBO;
private DataTable dataTable = new DataTable();
public ProgramPart()
{
InitializeComponent();
LoadDataParts();
}
public void LoadDataParts()
{
string sql3 = "SELECT * FROM Parts";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sql3, Con);
sqlDataAdapter.Fill(dataTable);
sqlDataAdapter.Dispose();
dataGridView1n.DataSource = dataTable;
}
private void TxtPP_GBC2_TextChanged(object sender, EventArgs e)
{
//DgvSearch(); //////// DgvSearch() works perferctly
try
{
if(txtPP_GBC2.Text == "")
{
dataTable.Clear();
LoadDataParts();
dataGridView1n.Refresh();
return;
}
(dataGridView1n.DataSource as DataTable).DefaultView.RowFilter = "GBC = '" + Convert.ToInt32(txtPP_GBC2.Text) + "'";
dataGridView1n.Refresh();
}
catch(Exception s)
{
MessageBox.Show(s.ToString());
}
}
private void DgvSearch()
{
string sql3 = "SELECT * FROM Parts WHERE GBC LIKE #GBC2 AND Description LIKE #DES";
Con.Open();
SqlDataAdapter da = new SqlDataAdapter(sql3, Con);
da.SelectCommand.Parameters.AddWithValue("#GBC2", SqlDbType.Int).Value = "%" + txtPP_GBC2.Text + "%";
da.SelectCommand.Parameters.AddWithValue("#DES", SqlDbType.VarChar).Value = "%" + txtPP_Description2.Text + "%";
DataSet ds = new DataSet();
da.Fill(ds, "Parts");
da.Dispose();
dataGridView1n.DataSource = ds;
dataGridView1n.DataMember = "Parts";
Con.Close();
}
}
You can use Convert expression function to convert value of the int column to the string and compare it using such filter:
private DataTable LoadData()
{
var dt = new DataTable();
dt.Columns.Add("C1", typeof(int));
dt.Rows.Add(1);
dt.Rows.Add(11);
dt.Rows.Add(2);
dt.Rows.Add(22);
return dt;
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = LoadData();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
var filter = "";
if (!string.IsNullOrEmpty(textBox1.Text))
filter = $"Convert([C1], System.String) = '{textBox1.Text}'";
(dataGridView1.DataSource as DataTable).DefaultView.RowFilter = filter;
}
If for any reason you prefer LIKE operator, you need to change the filter to:
filter = $"Convert([C1], System.String) LIKE '%{textBox1.Text}%'";

Add row from datagridview1 to datagridview2

I have two datagridviews in one from. I need to get data from database to datagridview1 (using Select *from database...) then I want to add data from datagriwview to datagridview2 using Selected Rows.
First I wanted to solve this problem to get Selected Row's ID, when I select row in datagridview it shows in datagridview2, but when I select another row, it is updating in datagridview, it does not add as new row. I tried several ways but did not solve this problem, Is there anyone help me to solve this problem? Thanks
private void dataGridView1_CellDoubleClick_1(object sender, DataGridViewCellEventArgs e)
{
int id = Convert.ToInt32
(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells["id"].Value);//3
try
{
MySqlConnection conn = new MySqlConnection(connection);
MySqlCommand command = start.CreateCommand();
command.CommandText = "SELECT id, muayine_adi, sabit_qiymet FROM tibbi_xidmetler WHERE id = '" + id.ToString() + "'";
conn.Open();
MySqlDataAdapter oxu = new MySqlDataAdapter(command);
DataTable dt = new DataTable();
oxu.Fill(dt);
dataGridView2.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Is quite simple the explanation: everytime that you make a double click to a datagridview1's cell you replace the old datatable with a new one. If you want append the result you can do something like this:
MySqlConnection conn = new MySqlConnection(connection);
MySqlCommand command = start.CreateCommand();
command.CommandText = "SELECT id, muayine_adi, sabit_qiymet FROM tibbi_xidmetler WHERE id = '" + id.ToString() + "'";
conn.Open();
MySqlDataAdapter oxu = new MySqlDataAdapter(command);
DataTable dt = new DataTable();
oxu.Fill(dt);
if(dataGridView2.DataSource != null) {
DataTable pr = dataGridView2.DataSource as DataTable;
pr.Merge(dt);
dataGridView2.DataSource = pr;
}
else
dataGridView2.DataSource = dt;
Since you have all information in datagridview1 you should just copy the contents of the selected row into a new row for datagridrow2.
The DataGridView is based on a DataSet which contains DataTables.
The DataTable contains rows.
You cannot move a row from one table to annother.
Instead you have to create a new row and insert into the DataTable of DataGridView2
private void dataGridView1_CellDoubleClick_1(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentRow.Cells["Id"].Value != null)
{
int Id = Convert.ToInt32(dataGridView1.CurrentRow.Cells["Id"].Value);
MySqlConnection start = new MySqlConnection(baglanti);
MySqlCommand command = start.CreateCommand();
command.CommandText = "SELECT id, muayine_adi, sabit_qiymet FROM tibbi_xidmetler WHERE id = '" + Id + "'";
start.Open();
MySqlDataAdapter oxu = new MySqlDataAdapter(command);
DataTable dt = new DataTable();
oxu.Fill(dt);
if (dt != null && dt.Rows.Count > 0)
{
int idx = dataGridView2.Rows.Count - 1;
dataGridView2.Rows.Add(dt.Rows.Count);
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
int rVal = (idx + i) + 1;
dataGridView2.Rows[rVal].Cells["id"].Value = dt.Rows[i]["id"].ToString();
dataGridView2.Rows[rVal].Cells["muayine_adi"].Value = dt.Rows[i]["muayine_adi"].ToString();
dataGridView2.Rows[rVal].Cells["sabit_qiymet"].Value = dt.Rows[i]["sabit_qiymet"].ToString();
}
}
start.Close();
}
}

Copy gridview rows in another gridview on a button_click

I have a textBox and a search button that fills the first Gridview. After that a Second Button Copies the first grid rows in the second grid . After that i should be able to search again in the first grid and attach the other results to the second grid.
But i get an error. Thnx in advance.
Here is my code:
public partial class Grid: System.Web.UI.Page
{
DataTable Dt = new DataTable();
private DataTable Dt1
{
set { ViewState.Add("Dt1", value); }
get { return (DataTable)ViewState["Dt1"]; }
}
private void Fill_grid()
{
string query = "Select * from table " +
" where field1 like '" + TextBox1.Text + "' or filed2 like '" +TextBox1.Text + "'";
SqlConnection cnn = new SqlConnection(...);
SqlCommand cmm = new SqlCommand(query,cnn);
cmm.CommandType = System.Data.CommandType.Text;
SqlDataAdapter MyDataAdapter = new SqlDataAdapter(cmm);
DataSet DS = new DataSet();
cnn.Open();
MyDataAdapter.Fill(DS, "Client");
Dt1 = DS.Tables["klient"];
DataView dv = new DataView(Dt1);
GridView2.DataSource = DS.Tables["klient"].DefaultView;
GridView2.DataBind();
}
protected void Button2_Click(object sender, EventArgs e)
{
Fill_grid();
}
protected void Button1_Click(object sender, EventArgs e)
{
Fill_Second_Grid();
}
private void Fill_Second_Grid()
{
DataRow dr;
foreach (GridViewRow row in GridView2.Rows)
{
dr = Dt.NewRow();
dr["Email"] = row.Cells[0].Text; ;
Dt.Rows.Add(dr);
}
GridView3.DataSource = Dt;
GridView3.DataBind();
}
}

How to filter gridview from textbox?

I need to filter a gridview that retreives filtered data from a table. Therefore I bound the gridview to a dataset. Now i can't seem to find a solution to filter it further.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds = new DataSet();
SqlConnection myCon = new SqlConnection(connectionstring);
SqlDataAdapter adapter = new SqlDataAdapter(cmd, myCon);
adapter.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//need to insert code here for filtering GridView1 based on TextBox1.Text
}
Thanks for the help.
Try this:
protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
SqlConnection myCon = new SqlConnection(connectionstring);
SqlDataAdapter adapter = new SqlDataAdapter(cmd, myCon);
adapter.Fill(ds);
DataView view = new DataView();
view.Table = ds.Tables[0];
view.RowFilter = "ColumnName = " + TextBox1.Text.Trim();
GridView1.DataSource = view;
GridView1.DataBind();
}
you have to refactor your code.
Here's a complete sample which handles GridView's paging, sorting(both directions) and filtering(two columns).
// store sorting across postbacks in a ViewState variable
public string SortExpression
{
get
{
if (ViewState["GridSort"]== null)
{
ViewState["GridSort"] = "Column1 ASC";
}
return ViewState["GridSort"].ToString();
}
set { ViewState["GridSort"] = value; }
}
protected void Page_load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGrid();
}
}
Here's the main method that does all (including the filter-function):
private void BindGrid()
{
try
{
var tblData = new DataTable();
var filter1 = TextBox1.Text.Trim();
var filter2 = TextBox2.Text.Trim();
using (var sqlCon = new System.Data.SqlClient.SqlConnection(connectionstring))
{
String sql = String.Empty;
var sqlCmd = new System.Data.SqlClient.SqlCommand();
if (filter1.Length != 0 && filter2.Length != 0)
{
sql = "SELECT Column1,Column2 FROM Table WHERE Column1 LIKE #Column1 AND Column2 LIKE #Column2 ORDER BY {0}";
sqlCmd.Parameters.AddWithValue("#Column1", string.Format("%{0}%", filter1));
sqlCmd.Parameters.AddWithValue("#Column2", string.Format("%{0}%", filter2));
}
else if (filter1.Length != 0)
{
sql = "SELECT Column1,Column2 FROM Table WHERE Column1 LIKE #Column1 ORDER BY {0}";
sqlCmd.Parameters.AddWithValue("#Column1", string.Format("%{0}%", filter1));
}
else if (filter2.Length != 0)
{
sql = "SELECT Column1,Column2 FROM Table WHERE Column2 LIKE #Column2 ORDER BY {0}";
sqlCmd.Parameters.AddWithValue("#Column2", string.Format("%{0}%", filter2));
}
else
{
// no filter, select all
sql = "SELECT Column1,Column2 FROM Table ORDER BY {0}";
}
sqlCmd.CommandText = string.Format(sql, this.SortExpression);
sqlCmd.Connection = sqlCon;
using (System.Data.SqlClient.SqlDataAdapter objAdapter = new System.Data.SqlClient.SqlDataAdapter(sqlCmd))
{
objAdapter.Fill(tblData);
}
}
GridView1.DataSource = tblData;
GridView1.DataBind();
}
catch (Exception)
{
// log
throw;
}
}
Paging:
private void GridView1_PageIndexChanging(object sender, System.Web.UI.WebControls.GridViewPageEventArgs e)
{
this.GridView1.PageIndex = e.NewPageIndex;
BindGrid();
}
Filter-Button-Click:
private void BtnFilter_Click(object sender, System.EventArgs e)
{
BindGrid();
}
Sorting:
protected void GridView1_Sorting(object sender, System.Web.UI.WebControls.GridViewSortEventArgs e)
{
string currentSortColumn = null;
string currentSortDirection = null;
currentSortColumn = this.SortExpression.Split(' ')[0];
currentSortDirection = this.SortExpression.Split(' ')[1];
if (e.SortExpression.Equals(currentSortColumn))
{
//switch sort direction
switch (currentSortDirection.ToUpper())
{
case "ASC":
this.SortExpression = currentSortColumn + " DESC";
break;
case "DESC":
this.SortExpression = currentSortColumn + " ASC";
break;
}
}
else
{
this.SortExpression = e.SortExpression + " ASC";
}
BindGrid();
}
Just converted from VB manually, so i hope there are no remaining errors.
sql = new SqlConnection(Connection.con);
adapter = new SqlDataAdapter(#"select EntryID * from Table where Name like #Name ", sql);
adapter.SelectCommand.Parameters.AddWithValue("#Name", string.Format("%{0}%", textBox1.Text));
dt = new DataTable();
adapter.Fill(dt);
dataGridView1.DataSource = dt;

Binding search results to data grid

I want to add search functionality to my program. There's a class which has this function:
public DataTable Search()
{
string SQL = "Select * from Customer where " + mField + " like '%" + mValue + "%'";
DataTable dt = new DataTable();
dt = dm.GetData(SQL);
return (dt);
}
There are setter and getter properties for mField and mValue. DM is the object of class DataManagement, which has a method GetData:
public DataTable GetData(string SQL)
{
SqlCommand command = new SqlCommand();
SqlDataAdapter dbAdapter = new SqlDataAdapter();
DataTable DataTable = new DataTable();
command.Connection = clsConnection.GetConnection();
command.CommandText = SQL;
dbAdapter.SelectCommand = command;
dbAdapter.Fill(DataTable);
return (DataTable);
}
The search functionality is currently implemented like this:
private void btnfind_Click(object sender, EventArgs e)
{
//cust is the object of class customer//
if (tbCustName.Text != "")
{
cust.Field="CustName";
cust.Value = tbCustName.Text;
}
else if (tbAddress.Text != "")
{
cust.Value = tbAddress.Text;
cust.Field="Address";
}
else if (tbEmail.Text != "")
{
cust.Value = tbEmail.Text;
cust.Field="Email";
}
else if (tbCell.Text != "")
{
cust.Value = tbCell.Text;
cust.Field = "Cell";
}
DataTable dt = new DataTable();
dt = cust.Search();
dgCustomer.DataSource = dt;
RefreshGrid();
}
private void RefreshGrid()
{
DataTable dt = new DataTable();
dt = cust.GetCustomers();
dgCustomer.DataSource = dt;
}
This is not working. I don't know why. Please help.
Add a DataBind() statement in your RefreshGrid() method to have your new results actually shown on the Grid.
private void RefreshGrid()
{
DataTable dt = cust.GetCustomers();
dgCustomer.DataSource = dt;
dgCustomer.DataBind();
}
Consider modifying your other method as well:
Your ad-hoc SQL has a SQL injection vulnerability. Stop everything until you fix that!
btnfind_Click doesn't need to end up calling cust.Search() twice.
private void btnfind_Click(object sender, EventArgs e)
{
//<snip>
// no need to do all this twice.
// DataTable dt = new DataTable();
// dt = cust.Search();
// dgCustomer.DataSource = dt;
RefreshGrid();
}
Your RefreshGrid method is overwriting the DataSource you set in btnfind_Click... don't call it, just call DataBind
private void btnfind_Click(object sender, EventArgs e)
{
...
DataTable dt = cust.Search();
dgCustomer.DataSource = dt;
dgCustomer.DataBind();
}
By the way, you don't need to assign a new DataTable to dt if you're immediately setting it to the result of cust.Search... you're just creating an instance for nothing (I fixed it in the code above)

Categories

Resources