search values from datatable (similer to like clause ) without using database - c#

public partial class WebForm4 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!(IsPostBack))
{
Session["List"] = null ;
}
}
public static DataTable dt;
public static int i = 1;
// static int i = 1;
//static List<string> lst;
protected void btnAdd_Click(object sender, EventArgs e)
{
Session["List"] = dt;
dt = new DataTable();
DataRow dr = null;
// dt.Columns.Add(new DataColumn("RowNumber", typeof(int)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
// dt.Columns.Add(new DataColumn("Column2", typeof(string)));
if (Session["List"] == null)
{
dr = dt.NewRow();
dr["Column1"] = txtAdd.Text;
dt.Rows.Add(dr);
// lst.Add(txtAdd.Text);
}
else if (Session["List"] != null)
{
dt = (DataTable)Session["List"];
dr = dt.NewRow();
dr["Column1"] = txtAdd.Text;
dt.Rows.Add(dr);
//lst = (List<string>)Session["List"];
//lst.Insert(i,txtAdd.Text);
//i++;
}
}
protected void btnNew_Click(object sender, EventArgs e)
{
List<string> lst = new List<string>();
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn col in dt.Columns)
{
lst.Add(row[col].ToString());
}
}
for (int j = 0; j >= dt.Rows.Count; j++)
{
}
bool isfound = lst.Contains(txtSearch.Text);
Response.Write(Convert.ToString(isfound));
dlshow.DataSource = dt; // i want to bind only matching values to datalist
dlshow.DataBind();
}
}
i have two textboxes one to add and other is to search i want to bind only those matching
values matches with search textbox ( Like ' Like ' clause ) i am not using any data base

//just this will do
protected void btnAdd_Click(object sender, EventArgs e)
{
List <string > lst = (List<string >)Session["List"];
lst.Add(txtAdd.Text);
// Change the list in session with new list
Session["List"] = lst;
}

Here the logic is wrong like you r testing if the session["list"] is null then u want to do the operation but if session is null then lst would also be null
List <string > lst = (List<string >)Session["List"];
lst.Add(txtAdd.Text);

DataTable dt2 = dt.Select("Column1 Like '%" + txtSearch.Text + "%'").CopyToDataTable();
dlshow.DataSource = dt2; // i want to bind only matching values to datalist
dlshow.DataBind();

Related

Deleting a row from datatable and displaying the updated gridview

Adding data in datatable from dropdown and displaying it in gridview. Then I am deleting a row and maintaining the ViewState but after deleting one row and mapping my values again I get the earlier state of the table in the gridview with duplicated records.
Here's the code:
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
//dt = new DataTable("tblTest");
//dt = ViewState["updatedtbl"] as DataTable;
DataColumn dc1 = new DataColumn();
dc1.DataType = typeof(String);
dc1.ColumnName = "A";
DataColumn dc2 = new DataColumn();
dc2.DataType = typeof(String);
dc2.ColumnName = "B";
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
//ViewState["dt"] = dt;
}
protected void Button2_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
if (Path.GetExtension(FileUpload1.FileName) == ".xlsx")
{
DataTable dt = new DataTable();
ExcelPackage package = new ExcelPackage(FileUpload1.FileContent);
dt = package.ToDataTable();
DropDownList1.Items.Clear();
for (int i = 0; i < dt.Columns.Count; i++)
{
DropDownList1.Items.Add(new ListItem(dt.Columns[i].ColumnName));
}
}
}
}
protected void Button3_Click(object sender, EventArgs e)
{
Session["A"] += DropDownList1.SelectedItem.Value + "|";
Session["B"] += DropDownList2.SelectedItem.Value + "|";
CreateTable();
}
public void CreateTable()
{
string[] sa = Session["A"].ToString().Split('|');
string[] sb = Session["B"].ToString().Split('|');
int recordnum = sa.Length;
for (int j = 0; j < recordnum - 1; j++)
{
DataRow dr = dt.NewRow();
dr["A"] = sa[j].ToString();
dr["B"] = sb[j].ToString();
dt.Rows.Add(dr);
}
ViewState["tbl"] = dt;
BindGrid();
}
protected void BindGrid()
{
GridView2.DataSource = dt;
GridView2.DataBind();
}
protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DataTable dx = ViewState["tbl"] as DataTable;
//DataTable dx = dt;
if (dx.Rows.Count > 0)
{
dx.Rows[e.RowIndex].Delete();
dx.AcceptChanges();
GridView2.DataSource = dx;
GridView2.DataBind();
ViewState["updatedtbl"] = dx;
}
else //To check which portion of code is being executed
{
Label1.Text = "Deleted";
Label2.Text = dx.Rows.Count.ToString();
}
}
In delete event you are reassigning the updated datatable to different viewstate with name updatedtbl. You should assign it to ViewState["tbl"].
if(dx.Rows.Count > 0)
{
dx.Rows[e.RowIndex].Delete();
dx.AcceptChanges();
GridView2.DataSource = dx;
GridView2.DataBind();
//ViewState["updatedtbl"] = dx; <<---- pay attention here
ViewState["tbl"] = dx; <<---- pay attention here
}

Pass gridview data(one page) to another page's gridview control using winforms

I have two pages in my windows application. Both pages have a gridview control. I can pass textbox values into 2nd form but my problem is, I dont know how to pass whole gridview data into 2nd form.
Form1:
public partial class Billing : Form
{
DataTable dt;
public Billing()
{
InitializeComponent();
SetDataTable();
txtBillNo.Text = Convert.ToString(billno);
}
public void btnEnter_Click(object sender, EventArgs e)
{
int row = dgvBilling.RowCount;
DataRow dr;
if (dgvBilling.RowCount != 0)
{
dr = dt.NewRow();
dr["IName"] = txtIName.Text.Trim();
dr["Icode"] = txtIcode.Text.Trim();
dr["Quantity"] = txtQuantity.Text.Trim();
dr["UnitPrice"] = txtUnitPrice.Text.Trim();
int amount = Convert.ToInt32(txtQuantity.Text.Trim()) * Convert.ToInt32(txtUnitPrice.Text.Trim());
dr["amount"] = Convert.ToString(amount);
dt.Rows.Add(dr);
int total = 0;
for (int i = 0; i < dgvBilling.Rows.Count; ++i)
{
total += Convert.ToInt32(dgvBilling.Rows[i].Cells[5].Value);
txtTotal.Text = "Rs/" + "" + Convert.ToString(total);
}
}
else
{
//dt = SetDataTable();
dr = dt.NewRow();
dr["IName"] = txtIName.Text.Trim();
dr["Icode"] = txtIcode.Text.Trim();
dr["Quantity"] = txtQuantity.Text.Trim();
dr["UnitPrice"] = txtUnitPrice.Text.Trim();
int amount = Convert.ToInt32(txtQuantity.Text.Trim()) * Convert.ToInt32(txtUnitPrice.Text.Trim());
dr["Amount"] = Convert.ToString(amount);
dt.Rows.Add(dr);
int total = 0;
for (int i = 0; i < dgvBilling.Rows.Count; ++i)
{
total += Convert.ToInt32(dgvBilling.Rows[i].Cells[5].Value);
txtTotal.Text = "Rs/" + "" + Convert.ToString(total);
}
RetrieveData();
}
}
public DataTable SetDataTable()
{
dt = new DataTable();
DataColumn dc = new DataColumn("IName", typeof(string));
dt.Columns.Add(dc);
dc = new DataColumn("Icode", typeof(string));
dt.Columns.Add(dc);
dc = new DataColumn("Quantity", typeof(string));
dt.Columns.Add(dc);
dc = new DataColumn("UnitPrice", typeof(string));
dt.Columns.Add(dc);
dc = new DataColumn("Amount", typeof(string));
dt.Columns.Add(dc);
DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
checkBoxColumn.HeaderText = "";
checkBoxColumn.Width = 50;
checkBoxColumn.Name = "checkBoxColumn";
dgvBilling.Columns.Insert(0, checkBoxColumn);
dgvBilling.DataSource = dt;
return dt;
}
private void btnPrintBill_Click(object sender, EventArgs e)
{
PrintBill pb = new PrintBill();
pb.Controls["lblNetAmount"].Text = txtTotal.Text;
pb.Show();
}
}
}
form2:
public partial class PrintBill : Form
{
public PrintBill()
{
InitializeComponent();
Billing bg = new Billing();
dataGridView1.DataSource = bg.RetrieveData();
}
}
When I click PrintBill button I want to show 2nd form with the gridview values of first form...
As a good option you can use a DataTable as data source of your DataGridView and when you need to pass data to other form, use Copy method of that DataTable. Here is an example:
Your GridForm:
public partial class GridForm : Form
{
public GridForm()
{
InitializeComponent();
}
//we will this as data source
private DataTable table;
private void GridForm_Load(object sender, EventArgs e)
{
//Create the data table here and bind it to grid
table = new DataTable();
table.Columns.Add(new DataColumn("IName", typeof(string)));
table.Columns.Add(new DataColumn("Icode", typeof(string)));
table.Columns.Add(new DataColumn("Quantity", typeof(string)));
table.Columns.Add(new DataColumn("UnitPrice", typeof(string)));
table.Columns.Add(new DataColumn("Amount", typeof(string)));
this.dataGridView1.DataSource = table;
}
private void passDataButton_Click(object sender, EventArgs e)
{
//When you need to pass data, use Copy method of data table
var clone = table.Copy();
//Pass data to other form
var f = new OtherForm(clone);
f.ShowDialog();
}
}
Your OtherForm:
public partial class OtherForm : Form
{
DataTable table;
public OtherForm(DataTable value)
{
InitializeComponent();
//get passed data and put it in some member variable for next usages
table = value;
//Bind data to other grid or do other things here or in Form Load event
this.dataGridView1.DataSource = table;
}
}
Actually, you can make that datarow/DataTable a global variable to make it accessible to other class. And also, you can create a public method that returns a datatable like :
public DataTable RetrieveData()
{
DataTable dt;
//retrive necessary data here
return dt;
}

Duplicate Values in Gridview if on different page of the gridview

I am having a Gridview with 1 checkbox column and 3 other columns. To 1 colums I am adding values from a TextBox on ButtonClick.
I want that duplicate values should not displayed in the gridview for which I have added code in Rowdatabound.
The code works perfectly when paging is disabled but when paging is enabled code works only if a duplicate value is added to the same page but if the value being added is to the next page the value is accepted.
protected void GVRequest_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//switch for first row
if (e.Row.RowIndex == 1)
{
GridViewRow Gprev = GVRequest.Rows[e.Row.RowIndex - 1];
if (Gprev.Cells[1].Text.Equals(e.Row.Cells[1].Text))
{
e.Row.Cells[1].Text = "";
e.Row.Visible = false;
}
}
//now continue with the rest of the rows
if (e.Row.RowIndex > 1)
{
//set reference to the row index and the current value
int intC = e.Row.RowIndex;
string lookfor = e.Row.Cells[1].Text;
//now loop back through checking previous entries for matches
do
{
GridViewRow Gprev = GVRequest.Rows[intC - 1];
if (Gprev.Cells[1].Text.Equals(e.Row.Cells[1].Text))
{
//e.Row.Cells[0].Text = "";
//e.Row.Cells[1].Text = "";
//e.Row.Cells[2].Text = "";
//e.Row.Cells[3].Text = "";
e.Row.Visible = false;
//Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('ID already added for processing');", true);
}
intC = intC - 1;
} while (intC > 0);
}
}
}
protected void GVRequest_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
//DataRow drCurrentRow = null;
GVRequest.PageIndex = e.NewPageIndex;
GVRequest.DataSource = dtCurrentTable;
//SetPreviousData();
//GVRequest.DataBind();
DataBind();
}
//Add new Row
private void AddNewRowToGrid()
{
if (ViewState["CurrentTable"] != null)
{
try
{
string RequestID = Request.QueryString["RequestID"];
SqlConnection conn = new SqlConnection(GetConnectionString());
StringBuilder sb = new StringBuilder(string.Empty);
const string SQLFileRetrievalReq = "SELECT DeptFileID, FileStatus, FileID, RequestID FROM FileInwardMaster WHERE (FileID = #FileID) AND (RequestID = #RequestID)";
SqlCommand cmdFileRetrievalReq = new SqlCommand(SQLFileRetrievalReq, conn);
cmdFileRetrievalReq.Parameters.Add("#RequestID", SqlDbType.VarChar);
cmdFileRetrievalReq.Parameters["#RequestID"].Value = RequestID;
cmdFileRetrievalReq.Parameters.Add("#FileID", SqlDbType.VarChar);
cmdFileRetrievalReq.Parameters["#FileID"].Value = TextBoxFileIds.Text.ToString();
conn.Open();
SqlDataReader reader = cmdFileRetrievalReq.ExecuteReader();
reader.Read();
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
drCurrentRow = dtCurrentTable.NewRow();
//drCurrentRow["SlNo"] = dtCurrentTable.Rows.Count + 1;
drCurrentRow["FileID"] = TextBoxFileIds.Text.ToUpper();
drCurrentRow["RequestID"] = RequestID;
drCurrentRow["DeptFileID"] = reader["DeptFileID"].ToString();
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
GVRequest.DataSource = dtCurrentTable;
GVRequest.DataBind();
}
catch
{
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('ID Entered/Scanned not valid for Request. Please Enter/Scan a valid ID to proceed');", true);
SetPreviousData();
//SetInitialRow();
//GVRequest.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}
//Get Previous Data
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
dt.Rows[i]["FileID"].ToString();// = txtRcptHdNo.Text;
dt.Rows[i]["RequestID"].ToString();// = ddlRcptDtlsItem.SelectedItem.Text;
dt.Rows[i]["DeptFileID"].ToString();// = ddlRcptDtlsItem.SelectedItem.Text;
rowIndex++;
}
}
}
}
private void SetInitialRow()
{
string RequestID = Request.QueryString["RequestID"];
DataTable dt = new DataTable();
//DataRow dr = null;
dt.Columns.Add(new DataColumn("RequestID", typeof(string)));
dt.Columns.Add(new DataColumn("FileID", typeof(string)));
dt.Columns.Add(new DataColumn("DeptFileID", typeof(string)));
// dr = dt.NewRow();
// dr["RequestID"] = string.Empty;
//dr["FileID"] = string.Empty;
//dr["DeptFileID"] = string.Empty;
//dt.Rows.Add(dr);
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
GVRequest.DataSource = dt;
GVRequest.DataBind();
}
protected void BtnAddFileID_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
//GenerateUniqueData(0);
TextBoxFileIds.Text = "";
}

fill grid view from textbox and dropddown list values recursively on each button click

I want to fill grid view with textbox and dropddown list values recursively on button click.Currently it is binding only once.I am new to ASP.NET.Help would be highly appreciated
protected void btnAdd_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("Resource");
dt.Columns.Add("available");
for (int intCnt = 0; intCnt < grd.Rows.Count - 1; intCnt++)
{
if (grd.Rows[intCnt].RowType == DataControlRowType.DataRow)
{
dr = dt.NewRow();
dr["Resource"] = grd.Rows[intCnt].Cells[0];
dr["available"] = grd.Rows[intCnt].Cells[1];
dt.Rows.Add(dr);
}
}
dr = dt.NewRow();
dr["Resource"] = ddlResource.SelectedItem.Text;
dr["available"] = txtavailable.Text;
dt.Rows.Add(dr);
grd.DataSource = dt;
grd.DataBind();
}
Please try this hope it will help
protected void btnAdd_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("Resource");
dt.Columns.Add("available");
foreach(GridViewRow row in grd.Rows)
{
dr = dt.NewRow();
dr["Resource"] = row.Cells[0].Text;
dr["available"] =row.Cells[1].Text;
dt.Rows.Add(dr);
}
dr = dt.NewRow();
dr["Resource"] = ddlResource.SelectedItem.Text;
dr["available"] = txtavailable.Text;
dt.Rows.Add(dr);
grd.DataSource = dt;
grd.DataBind();
}
Use following code:
protected void btnAdd_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt = defineColumn();
DataRow dr;
foreach (GridViewRow grow in grdChMedicine.Rows)
{
dr = dt.NewRow();
dr["Diagnosis"] = grow.Cells[1].Text;
dr["DiagnosisId"] = grow.Cells[2].Text;
dt.Rows.Add(dr);
}
dr = dt.NewRow();
dr["Diagnosis"] = ddldiagnosis.SelectedItem.ToString();
dr["DiagnosisId"] = ddldiagnosis.SelectedValue;
dt.Rows.Add(dr);
ViewState["ChMedicine"] = dt;
grdChMedicine.DataSource = dt;
grdChMedicine.DataBind();
}
private DataTable defineColumn()
{
DataTable dt = new DataTable();
dc = new DataColumn("Diagnosis");
dt.Columns.Add(dc);
dc = new DataColumn("DiagnosisId");
dt.Columns.Add(dc);
return dt;
}

Filling DataTable from GridView in C#

How can I fill DataTable from GridView in ASP.NET?
Simply, you can do like this:
BindingSource bindingSource = (BindingSource )yourGridView.DataSource;
DataTable yourDataTable= (DataTable ) bindingSource .DataSource;
Another way, you can do like this:
DataTable yourDataTable = yourGridView.DataSource as DataTable
I solved like this
if (myGridView.Rows.Count > 0)
{
var dt = new DataTable();
dt.Columns.Add("Column1", typeof(string));
dt.Columns.Add("Column2", typeof(Int64));
dt.Columns.Add("Column3", typeof(string));
foreach (GridViewRow row in gd_endYearSchool.Rows)
{
var id = row.Cells[1].Text;
//for find textbox
var tb1 = row.Cells[2].FindControl("tbNr") as TextBox;
int nrord = 0;
if (tb1 != null)
{
var ord = tb1.Text;
if (!Int64.TryParse(ord, out nrord))
{
nrord = 0;
}
}
var text=row.Cell[3].text;
dt.Rows.Add(id,nrord,text);
}
}
you can fill datatable from gridview with foreach
I'll do like this, i think this'll help u.
public void Data_table()
{
Session["Data"] = "";
DataTable dt = new DataTable();
//Add Columns to the datatable
dt.Columns.Add("c1");
dt.Columns.Add("c2");
dt.Columns.Add("c3");
//Define a datarow for the datatable dt
DataRow dr = dt.NewRow();
//Now add the datarow to the datatable
Session["Data"] = dt;
RadGrid1.DataSource = dt;
RadGrid1.Rebind();
}
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
if (((System.Data.DataTable)(Session["Data"])).Rows.Count.ToString() != "")
{
RadGrid1.DataSource = Session["Data"];
}
}
Thank you..,

Categories