Perform search in 3tier architecture - c#

i am all confused in 3 tier
without using 3 tier this function worked
DataTable dt;
private void textBox1_TextChanged(object sender, EventArgs e)
{
DataView dv = new DataView(dt);
dv.RowFilter = string.Format("emp_f_name LIKE '%{0}%'",textBox1.Text);
dataGridView1.DataSource = dv;
}
BUt in 3 tier
i am all confused can u guys help me rewrite the code i am trying to search firstname in a textbox
in my bll class
public DataTable Display(string fname)
{
try
{
return obj.Display(fname);
}
catch (Exception ex)
{
throw ex;
}
}
in my dal class
public DataTable Display(string fname)
{
string query2;
OpenCnn();
query2 = "SELECT * FROM cntc_employee where fname='" +fname + "' ";
sda = new SqlDataAdapter(query2, con);
dt = new DataTable();
sda.Fill(dt);
CloseCnn();
return dt;
}
in ui class
private void textBox1_TextChanged(object sender, EventArgs e)
{
string fname = txtfname.Text;
DataView dv = new DataView(dt);
dt = obj.Display(fname);
dv.RowFilter = string.Format("emp_f_name LIKE '%{0}%'", textBox1.Text);
dataGridView1.DataSource = dv;
this.dataGridView1.DataSource = obj.Display(this.txtfname.Text);
}

Is this what you want?
Your BLL class should be like this
public DataTable Display(string fname)
{
try
{
DataTable dt = obj.Display(fname);//call to DAL
DataView dv = new DataView(dt);
dv.RowFilter = string.Format("emp_f_name LIKE '%{0}%'",
textBox1.Text);
return dv.ToTable();
}
catch (Exception ex)
{
throw ex;
}
}
In your UI
private void textBox1_TextChanged(object sender, EventArgs e)
{
string fname = txtfname.Text;
dt = obj.Display(fname);// Call to BLL
dataGridView1.DataSource = dt;
}
in your DAL class
public DataTable Display(string fname)
{
string query2;
OpenCnn();
query2 = "SELECT * FROM cntc_employee where fname='" +fname + "' ";
sda = new SqlDataAdapter(query2, con);
dt = new DataTable();
sda.Fill(dt);
CloseCnn();
return dt;
}

Related

C# System.Data.DataRowView

I am almost there trying to filter my datagridview from a combobox avoiding to using the databinding GUI. My problem is now that I see System.Data.DataRowView in my combobox inxtead of the normal values. The code:
private void Form2_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data SourceXXXXX;Initial Catalog=Studio;Integrated Security=True;");
conn.Open();
SqlCommand sc = new SqlCommand("SELECT Nome FROM DClub order by Nome", conn);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("Nome", typeof(string));
dt.Load(reader);
comboBox1.ValueMember = "Nome";
comboBox1.DisplayMember = "Nome";
comboBox1.DataSource = dt;
conn.Close();
var select = "SELECT *,bell+corp+fasc+app as Obi, bell+corp+fasc+vic+app as Tot,(bell+corp+fasc+vic+app)/5 as Med, (bell+corp+fasc+app)/4 as MedOb FROM DClub order by bell+corp+fasc+vic+app desc";
var c = new SqlConnection("Data Source=DIEGOPC;Initial Catalog=Studio;Integrated Security=True;"); // Your Connection String here
var dataAdapter = new SqlDataAdapter(select, c);
var commandBuilder = new SqlCommandBuilder(dataAdapter);
var ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds.Tables[0];
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var dataView = ((DataTable)dataGridView1.DataSource).DefaultView;
if (comboBox1.Text == "Remove filter")
{
dataView.RowFilter = string.Empty;
}
else
{
dataView.RowFilter = $"Nome = '{comboBox1.Text}'";
}
}
}
}
In your last comment
combo1text contains the values retrieved from the query
is fine however what I meant was what does the string itself look like. I assume it is a string that would match one of the values in the Nome column? Without seeing what this “query” strings values are in the combo box, it is difficult to give a good answer. Below, I added a DataGridView and a ComboBox to a form then populated the DataGridView and ComboBox with two DataTables using some sample data. This seems to work as you describe. I assume the row filter line: dataView.RowFilter = $"Nome = '{comboBox1.Text}'"; is simply filtering on matches in DataTables Nome column. I hope the code below helps.
DataTable dgvData;
DataTable cbData;
public Form1() {
InitializeComponent();
dgvData = GetDVGData();
cbData = GetCBData(dgvData);
dataGridView1.DataSource = dgvData;
this.comboBox1.SelectedIndexChanged -= new System.EventHandler(this.comboBox1_SelectedIndexChanged);
comboBox1.DisplayMember = "Filter";
comboBox1.ValueMember = "Filter";
comboBox1.DataSource = cbData;
this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
}
private DataTable GetCBData(DataTable inDT) {
DataTable dt = new DataTable();
dt.Columns.Add("Filter", typeof(string));
dt.Rows.Add("Remove Filter");
foreach (DataRow dr in inDT.Rows) {
dt.Rows.Add(dr.ItemArray[1].ToString());
}
return dt;
}
private DataTable GetDVGData() {
DataTable dt = new DataTable();
dt.Columns.Add("Number");
dt.Columns.Add("Name");
dt.Columns.Add("Address");
dt.Rows.Add("1", "John", "Texas");
dt.Rows.Add("2", "Mary", "Florida");
dt.Rows.Add("3", "Tom", "New York");
dt.Rows.Add("4", "Marvin", "Moon");
dt.Rows.Add("5", "Jason", "Holland");
dt.Rows.Add("6", "Teddy", "New York");
return dt;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
var dataView = ((DataTable)dataGridView1.DataSource).DefaultView;
if (comboBox1.Text == "Remove Filter") {
dataView.RowFilter = string.Empty;
}
else {
dataView.RowFilter = $"Name = '{comboBox1.Text}'";
}
}

C# How to apply row filter after refresh dataGridView

I can save the current dataGridView scroll and focus position but it doesn't work when I apply a filter. How can I apply the row filter or keep the selected row after refresh datagridview?
public void button_refresh_Click(object sender, EventArgs e)
{
int row = (this.dataGridView1.CurrentCell.RowIndex);
int col = (this.dataGridView1.CurrentCell.ColumnIndex);
int scroll = dataGridView1.FirstDisplayedCell.RowIndex;
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from PPAPdatabase";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show("An error has occurred: " + ex.Message,
"Important Note",
MessageBoxButtons.OK,
MessageBoxIcon.Error,
MessageBoxDefaultButton.Button1);
}
finally
{
connection.Close();
}
dataGridView1.Sort(dataGridView1.Columns[0], ListSortDirection.Descending);
this.dataGridView1.CurrentCell = this.dataGridView1[col, row];
dataGridView1.FirstDisplayedScrollingRowIndex = scroll;
}
Filter:
private void text_Pnumber_TextChanged(object sender, EventArgs e)
{
DataView dv = new DataView(dt);
dv.RowFilter = string.Format("[Part Number] LIKE '%{0}%'", text_Pnumber.Text);
dataGridView1.DataSource = dv;
}
Any help would be appreciated!

Update not working from grid view (not able to get the error )

I'm trying to update a table from the gridview of tool to the SQL database. The problem is it's not getting updated in the database.
Below is my code for the button click which updates the database:
while debugging the code i found that the data table DT is fetching only the source values not the updated one in the grid view....
Is there any property in the grid view which accepts these change and updates the DT table ?
public partial class BusinessRules : Form
{
//Declaration Part
private SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=AnimalProductsCoSD;Integrated Security=True");
private string sqlconn; // query and sql connection
private SqlDataAdapter SDA = new SqlDataAdapter();
DataTable DT = new DataTable();
SqlCommandBuilder scb = new SqlCommandBuilder();
private void button_retreive_Click(object sender, EventArgs e)
{
string commandText = "CoSD.RetreiveBusinessRulesTool";
SqlCommand cmd = new SqlCommand(commandText, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#BusinessType", SqlDbType.NVarChar, 60).Value = comboBox_BusinessType.Text;
cmd.Parameters.Add("#CommodityGroup", SqlDbType.VarChar, 60).Value = comboBox_group.Text;
try
{
con.Open();
SDA.SelectCommand = cmd;
DT = new DataTable();
SDA.Fill(DT);
int count1 = DT.Rows.Count;
if (DT.Rows.Count > 0)
{
dataGridView.DataSource = DT;
dataGridView.Columns[0].DefaultCellStyle.ForeColor = Color.Gray;
dataGridView.Columns[0].ReadOnly = true;
}
else
{
MessageBox.Show("No Business Rules Found");
}
}
catch (SqlException ex)
{
MessageBox.Show("Error : " + ex.Message);
}
finally
{
con.Close();
}
}
private void button_update_Click(object sender, EventArgs e)
{
try
{
if (MessageBox.Show("Do you really want to Update these values?", "Confirm Update", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
scb = new SqlCommandBuilder(SDA);
SDA.Update(DT);
// confirm
MessageBox.Show("Updates successfully submitted to CoSD");
}
else
{
return;
}
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
}
In the try, put this
scb = new SqlCommandBuilder(sda);
sda.Update(dt);
In your initializer call
SqlDataAdapter sda= new SqlDataAdapter("SELECT * FROM someWhere", connectionString);
DataTable dt = new DataTable();
The problem is that you refresh the datagridview before submitting the changes, thus deleting anything inputted
**** EDIT ****
This is exactly what my code in a project I did a little while back looks like:
namespace TowerSearch
{
public partial class EditParts : Form
{
const string conString = ConString.conString;
static DataClasses1DataContext PartsLog = new DataClasses1DataContext(conString);
static Table<Part> listOfParts = PartsLog.GetTable<Part>();
SqlDataAdapter sda;
SqlCommandBuilder scb;
DataTable dt;
public EditParts()
{
InitializeComponent();
}
//Load and refresh the dataGridView
private void showData()
{
SqlConnection con = new SqlConnection(conString);
sda = new SqlDataAdapter("SELECT * FROM Parts", con);
dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
private void EditParts_Load(object sender, EventArgs e)
{
showData();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
dataGridView1.Refresh();
scb = new SqlCommandBuilder(sda);
sda.Update(dt);
MessageBox.Show("Saved");
showData();
}
catch (Exception ee)
{
MessageBox.Show("There is an error in the data!\nCheck if there are any blank spots besides Quantity.");
}
}
}
}
That definitely works, so try the code with the show data. I'd suggest just copying it verbatim first to see if it would work.
**** EDIT 2 ****
Another thing that you could try if you haven't managed to get it already is add a bindingSource. To do this, drag a bindingSource onto your dataGridView and then set the DataSource option to the table of the DB that you wan't to display
Hope that helps!

Sorting column in a GridView

Below is my code C# net4 for sorting column in GridView but I've this error:
CS1502: The best overloaded method match for System.Data.DataView.DataView(System.Data.DataTable) has some invalid arguments
in this line why?: DataView sortedView = new DataView(GridViewBind());
public SortDirection dir
{
get
{
if (ViewState["dirState"] == null)
{
ViewState["dirState"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["dirState"];
}
set
{
ViewState["dirState"] = value;
}
}
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
string sortingDirection = string.Empty;
if (dir == SortDirection.Ascending)
{
dir = SortDirection.Descending;
sortingDirection = "Desc";
}
else
{
dir = SortDirection.Ascending;
sortingDirection = "Asc";
}
DataView sortedView = new DataView(GridViewBind());
sortedView.Sort = e.SortExpression + " " + sortingDirection;
GridView1.DataSource = sortedView;
GridView1.DataBind();
}
public void GridViewBind()
{
sql1 = " SELECT * FROM `tbl` ORDER BY empid DESC; ";
dadapter = new OdbcDataAdapter(sql1, myConnectionString);
dset = new DataSet();
dset.Clear();
dadapter.Fill(dset);
GridView1.DataSource = dset.Tables[0];
GridView1.DataBind();
dadapter.Dispose();
dadapter = null;
myConnectionString.Close();
}
The error is due to this line
DataView sortedView = new DataView(GridViewBind());
The function GridViewBind() return type is void which is incorrect. It should return a DataTable.
If it returns DataTable then your code will work.
You need to modify your function as follow
public DataTable GridViewBind()
{
sql1 = " SELECT * FROM `tbl` ORDER BY empid DESC; ";
dadapter = new OdbcDataAdapter(sql1, myConnectionString);
dset = new DataSet();
dset.Clear();
dadapter.Fill(dset);
DataTable dt=dset.Tables[0];
GridView1.DataSource = dt;
GridView1.DataBind();
dadapter.Dispose();
dadapter = null;
myConnectionString.Close();
return dt;
}
Use DataView to sot the data.
public void GridViewBind()
{
sql1 = " SELECT * FROM `tbl` ORDER BY empid DESC; ";
dadapter = new OdbcDataAdapter(sql1, myConnectionString);
dset = new DataSet();
dset.Clear();
dadapter.Fill(dset);
DataTable dt = new DataTable();
dt=dset.Tables[0];
DataView dv = dt.DefaultView;
dv.Sort = "empid desc";
DataTable sortedDT = dv.ToTable();
GridView1.DataSource = sortedDT;
GridView1.DataBind();
dadapter.Dispose();
dadapter = null;
myConnectionString.Close();
}

How to implement sorting functionality in gridview?

I am trying to implement sorting functionality in grid view but its not working..
Code:
//enter code here
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
SqlCommand cmd;
DataSet ds;
SqlDataAdapter da;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["myDataSet"] = FillDataSet();
}
}
private string ConvertSortDirectionToSql(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;
case SortDirection.Descending:
newSortDirection = "DESC";
break;
}
return newSortDirection;
}
protected DataSet FillDataSet()
{
string source = "Database=GridTest;Server=Localhost;Trusted_Connection=yes";
con = new SqlConnection(source);
cmd = new SqlCommand("proc_mygrid", con);
ds = new DataSet();
da = new SqlDataAdapter(cmd);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
return ds;
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//DataSet ds = FillDataSet();
DataTable dt = ((DataSet)Session["myDataSet"]).Tables[0];
if (dt != null)
{
dt.DefaultView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
GridView1.DataSource = dt;
GridView1.DataBind();
}
Can somebody suggest where I am going wrong?
EDIT:
enter code here DataTable dtbl = ((DataSet)Session["myDataSet"]).Tables[0];
dtbl.DefaultView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
GridView1.DataSource = dtbl;
GridView1.DataBind();
Here is the running code:
private string GetSortDirection(string column)
{
string sortDirection = "DESC";
string sortExpression = ViewState["SortExpression"] as string;
if (sortExpression != null)
{
if (sortExpression == column)
{
string lastDirection = ViewState["SortDirection"] as string;
if ((lastDirection != null) && (lastDirection == "DESC"))
{
sortDirection = "ASC";
}
}
}
ViewState["SortDirection"] = sortDirection;
ViewState["SortExpression"] = column;
return sortDirection;
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dtbl = ((DataSet)Session["myDataSet"]).Tables[0];
dtbl.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
GridView1.DataSource = dtbl;
GridView1.DataBind();
}

Categories