Passing value from labelbox to a linq query - c#

Hello guys i am new to linq and so is in .net. i want pass a value from label box to a linq query as parameter.below is the code ...
namespace PblCard.PublicWeb
{
public partial class Cardno : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
{
if (!IsPostBack)
{
if (Page.User.IsInRole(SecurityEngine.Roles.Customer))
{
Customer customer = new CustomerEngine().GetCustomerByEmail(Page.User.Identity.Name);
if (customer == null)
throw new ApplicationException(Properties.Resources.CustomerNotFound);
lblCardNo.Text = customer.CardNumber;
}
}
}
}
protected void ASPxButton2_Click(object sender, EventArgs e)
{
string panno = lblCardNo.Text;
using (Entities query = new Entities())
{
var txn = from p in query.TRANSACTIONs
.Where(x => x.PAN == panno)
select p;
GridView1.DataSource = txn;
GridView1.DataBind();
}
}
}
}
but when binding to grid i am not getting any output. but if i use this
protected void ASPxButton2_Click(object sender, EventArgs e)
{
string panno = lblCardNo.Text;
using (Entities query = new Entities())
{
var txn = from p in query.TRANSACTIONs
.Where(x => x.PAN == ("234567"))
select p;
GridView1.DataSource = txn;
GridView1.DataBind();
}
}
}
the grid is showing data. How should I write the query?

Databinding does not work with raw LINQ queries.
You need to write GridView1.DataSource = txn.ToList();

Add break point on panno to check if there is value pass from lblCardNo.Text.
string panno = lblCardNo.Text; <-- here
var txn = (from p in query.TRANSACTIONs
where Convert.ToString(p.PAN.ToString) == Convert.ToString(panno) <-- here
select p).ToList();
GridView1.DataSource = txn;
GridView1.DataBind();
then try to point to txn and check' results view' if it has a data.
Regards

Related

how to update data in webform using Gridview?

I want to give my user a data table in which he/she can edit data.
I used this method to get my data from sql server
public static List<TestAsfa> GetRecordsMan() {
using (var d = new TestEntities())
{
return d.TestAsfa.ToList();
}
I got stuck when I wanted to write the Delete Function
protected void RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
dt.Rows[GridView1.Rows[e.RowIndex].RowIndex].Delete();
int id =Convert.ToInt32(GridView1.Rows[e.RowIndex].ID);
FillGridView();
}
catch
{
Response.Write("<script> alert('Record not deleted...') </script>");
}
}
this is the delete function. I wrote the method below
public static void deleteRecord(int id)
{
using (var d = new TestEntities())
{
TestAsfa tb = d.TestAsfa.SingleOrDefault(t => t.ID == id);
d.TestAsfa.Remove(tb);
d.SaveChanges();
}
}
but I don't know it doesn't get the correct row id from sender
I don't understand my mistake
Don't forget to prevent error you'll need to ensure that the id you're checking on is of an actual Item. Something like this, for example:
public static void deleteRecord(TestAsfa TA,int id)
{
using(var d = new TestEntities())
{
TA= d.TestAsfa.Where(item => item.ItemId == id).FirstOrDefault();
if (itemTA!= null) {
d.TestAsfa.Remove(TA);
}
}
}
For removing selected row use this code
using(var d = new TestEntities())
{
d.TestAsfa.Remove(d.TestAsfa.Find(id));
d.SaveChanges();
}
or use this one
using(var d = new TestEntities())
{
TestAsfa tb = d.TestAsfa.SingleOrDefault(t => t.Id == id);
d.TestAsfa.Remove(tb);
d.SaveChanges();
}
Hi try have a look at this
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lbldeleteid = (Label)row.FindControl("lblID");
conn.Open();
SqlCommand cmd = new SqlCommand("delete FROM tableName where
id='"+Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString())+"'", conn);
cmd.ExecuteNonQuery();
conn.Close();
gvbind();
}

Keep State of Gridview

I have a gridview and I'm trying to keep the state of. Currently I have it where the user can edit inline( from within the gridview). Regularly I got this working:
protected void GridViewTower_RowEditing(object sender, GridViewEditEventArgs e)
{
//Set the edit index.
GridViewTower.EditIndex = e.NewEditIndex;
//Bind/Re-LoadData data to the GridView control.
LoadData();
Populate();
}
protected void GridViewTower_CancelEditRow(object sender, GridViewCancelEditEventArgs e)
{
//Reset the edit index.
GridViewTower.EditIndex = -1;
//Bind/Re-LoadData data to the GridView control.
LoadData();
Populate();
}
Problem is, I have 3 other features such sorting, dropdown that filters gridview, and a button search which also filters the girdview. When inline editing within any 3 of those modes, I can't control the state in which the gridview is in. Inside my gridview tag, I have both EnableViewState and ViewStateMode set to true.
How can I keep the state of the gridview within these modes?
public void LoadData()
{
if (Session["GridView"] != null)
{
GridViewTower.DataSource = Session["GridView"];
GridViewTower.DataBind();
//Response.Redirect("TowerManagement.aspx"); //
//Session["GridView"] = null;
}
else
{
WISSModel.WISSEntities context = new WISSModel.WISSEntities();
var tower = (from t in context.Towers
where t.isDeleted == false
select new
{
t.TowerId,
t.TowerName,
RangeName = t.Range.RangeName
}).ToList();
GridViewTower.DataSource = tower;
GridViewTower.DataBind();
ViewState["Sort"] = 0;
}
}
protected void Gridview_Sort(object sender, GridViewSortEventArgs e)
{
WISSModel.WISSEntities context = new WISSModel.WISSEntities();
var towers = (from t in context.Towers
where t.isDeleted == false
select new
{
t.TowerId,
t.TowerName,
rangeName = t.Range.RangeName
}).ToList();
DataTable gridviewTable = towers.CopyToDataTable();
gridviewTable.DefaultView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
GridViewTower.DataSource = gridviewTable;
GridViewTower.DataBind();
Session["GridView"] = GridViewTower.DataSource;
}
You don't need to store whole table in the Session or ViewState. Just store values of SortExpression, SortOrder etc. Here's an example how you can do it.
In my code I have added two private properties to store sortorder and sortexpression:
private string SortOrder
{
get
{
// Toggle order after sorting
string _order = "ASC";//Default
if( ViewState["SortOrder"] != null && ViewState["SortOrder"].ToString() =="DESC")
{
_order = "DESC";
ViewState["SortOrder"] = "ASC";
}
else
{
ViewState["SortOrder"] = "DESC";
}
return _order;
}
set
{
string _order = value.ToLower() == "descending"? "DESC" : "ASC";
ViewState["SortOrder"] = _order;
}
}
private string SortExpression
{
get
{
return ViewState["SortExpression"] != null ? ViewState["SortExpression"].ToString() : "";
}
set
{
ViewState["SortExpression"] = value;
}
}
I have changed your GridView_Sort method to store the sort expression and sort order in newly added properties and called LoadData() method:
protected void Gridview_Sort(object sender, GridViewSortEventArgs e)
{
SortExpression = e.SortExpression;
//Disabled sort direction to enable toggling
//SortOrder = e.SortDirection.ToString();
LoadData();
}
The LoadData() method will be called from many places, whenever we want to load data into GridView. So I have changed it to this:
public void LoadData()
{
WISSModel.WISSEntities context = new WISSModel.WISSEntities();
var towers = (from t in context.Towers
where t.isDeleted == false
select new
{
t.TowerId,
t.TowerName,
rangeName = t.Range.RangeName
}).ToList();
DataTable gridviewTable = new DataTable();
gridviewTable.Columns.Add("TowerId");
gridviewTable.Columns.Add("TowerName");
gridviewTable.Columns.Add("rangeName");
foreach (var t in towers)
{
gridviewTable.Rows.Add(new object[] { t.TowerId, t.TowerName, t.rangeName });
}
if (!String.IsNullOrEmpty(SortExpression))
{
gridviewTable.DefaultView.Sort = String.Format("{0} {1}", SortExpression, SortOrder);
gridviewTable = gridviewTable.DefaultView.ToTable();
}
GridViewTower.DataSource = gridviewTable;
GridViewTower.DataBind();
}
Initially I call the LoadData() method in Page_Load() :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadData();
}
}
You can download the test project here.

Textbox autocomplete function not autocompleting in C# WinForm Application

Im having problems with this simple function on a textbox.. I have a winforms application, with a textbox, set up to autocomplete like this:
if (rbSerialNumSearch.Checked)
{
txtSerialNum.Enabled = true;
AutoCompleteStringCollection data = new AutoCompleteStringCollection();
//Test data
data.Add("555-777-333");
data.Add("222-333-444");
data.Add("111-222-333");
txtSerialNum.AutoCompleteCustomSource = data;
txtSerialNum.AutoCompleteMode = AutoCompleteMode.Suggest;
txtSerialNum.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
But it is not working. Nothing appears when i type in the textbox? If i i specify strings directly to the textbox collection property (in design mode), it works fine, but when i try to add strings programmatically, nothing happends?
Thanks in advance..
ENTIRE CODE FOR FORM HERE:
namespace GUI
{
public partial class UpdateEquipmentForm : Form
{
EquipmentManager em;
ProductManager pm;
CategoryManager cm;
public UpdateEquipmentForm()
{
InitializeComponent();
em = new EquipmentManager();
pm = new ProductManager();
cm = new CategoryManager();
}
private void btnSearch_Click(object sender, EventArgs e)
{
if (rbCategorySearch.Checked)
{
List<Equipment> equipments = em.GetAllEquipmentInStock().Where(eq => eq.Product.Category_Id == (int)cbChooseCategory.SelectedValue).ToList();
var resultset = (from eq in equipments
select new { eq.Product.ProductNameNum, eq.Id, eq.SerialNumber, eq.InvoiceNumber, eq.CreatedDate, eq.ExpiryDate, eq.FirstUseDate }).ToList();
dgvResult.DataSource = resultset;
}
if (rbProductsSearch.Checked)
{
List<Equipment> equipments = em.GetAllEquipmentInStock().Where(eq => eq.Product.Id == (int)cbChooseType.SelectedValue).ToList();
var resultset = (from eq in equipments
select new { eq.Product.ProductNameNum, eq.Id, eq.SerialNumber, eq.InvoiceNumber, eq.CreatedDate, eq.ExpiryDate, eq.FirstUseDate }).ToList();
dgvResult.DataSource = resultset;
}
if (rbSerialNumSearch.Checked)
{
List<Equipment> equipments = em.GetAllEquipmentInStock();
var resultset = (from eq in equipments
where eq.SerialNumber.Contains(txtSearchEquipment.Text)
select new { eq.Product.ProductNameNum, eq.Id, eq.SerialNumber, eq.InvoiceNumber, eq.CreatedDate, eq.ExpiryDate, eq.FirstUseDate }).ToList();
dgvResult.DataSource = resultset;
}
}
private void rbCategorySearch_CheckedChanged(object sender, EventArgs e)
{
if (rbCategorySearch.Checked)
{
cbChooseCategory.Enabled = true;
cbChooseCategory.DataSource = cm.GetAllActiveCategories();
cbChooseCategory.DisplayMember = "Name";
cbChooseCategory.ValueMember = "Id";
}
else
{
cbChooseCategory.Enabled = false;
}
}
private void rbProductsSearch_CheckedChanged(object sender, EventArgs e)
{
if (rbProductsSearch.Checked)
{
cbChooseType.Enabled = true;
cbChooseType.DataSource = pm.GetAllActiveProducts();
cbChooseType.DisplayMember = "ProductNameNum";
cbChooseType.ValueMember = "Id";
}
else
{
cbChooseType.Enabled = false;
}
}
private void rbSerialNumSearch_CheckedChanged(object sender, EventArgs e)
{
if (rbSerialNumSearch.Checked)
{
txtSerialNum.Enabled = true;
AutoCompleteStringCollection data = new AutoCompleteStringCollection();
data.Add("555-777-333");
data.Add("222-333-444");
data.Add("111-222-333");
txtSerialNum.AutoCompleteCustomSource = data;
txtSerialNum.AutoCompleteMode = AutoCompleteMode.Suggest;
txtSerialNum.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
else
{
txtSerialNum.Enabled = false;
}
}
}
}
Found the problem.. Really stupid of me. I was referencing the wrong textbox :-( The one i should be referencing is called txtSearchSerial and not txtSerialNum. Doh !
Appreciate the effort guys..thanks.
You can set a break point to
txtSerialNum.Enabled = true;
I think this application never run into this block.
Or after this code, you re-set the binding of txtSerialNum.

Updating data into Database

I have problems adding data into the database. The code that I have written could only update the shiftTiming_Start but not the shiftTiming_Stop. Can someone please help take a look at my code and see what went wrong. Thanks a lot.
private void btnUpdate_Click(object sender, EventArgs e) {
using (testEntities Setupctx = new testEntities()) {
var toBeUpdated = txtStart.Text;
var toBeUpdated1 = txtStop.Text;
shifthour updateShift = new shifthour();
updateShift = Setupctx.shifthours.FirstOrDefault(u => u.shiftTiming_start == toBeUpdated);
updateShift = Setupctx.shifthours.FirstOrDefault(p => p.shiftTiming_stop == toBeUpdated1);
updateShift.shiftTiming_start = txtStart.Text;
updateShift.shiftTiming_stop = txtStop.Text;
Setupctx.SaveChanges();
txtStart.Text = "";
txtStop.Text = "";
MessageBox.Show("Shift Timing Has Been Updated.");
}
}
Assuming I'm following you correctly (I would recommend using more meaningful variable names), update the code as follows:
private void btnUpdate_Click(object sender, EventArgs e) {
using (testEntities Setupctx = new testEntities()) {
var toBeUpdatedStart = txtStart.Text;
var toBeUpdatedStop = txtStop.Text;
shifthour updateStartShift;
shifthour updateStopShift;
updateStartShift = Setupctx.shifthours.FirstOrDefault(u => u.shiftTiming_start == toBeUpdatedStart);
updateStopShift = Setupctx.shifthours.FirstOrDefault(p => p.shiftTiming_stop == toBeUpdatedStop);
if (updateStartShift != null)
{
updateStartShift.shiftTiming_start = txtStart.Text;
}
if (updateStopShift != null)
{
updateStopShift.shiftTiming_stop = txtStop.Text;
}
Setupctx.SaveChanges();
txtStart.Text = "";
txtStop.Text = "";
MessageBox.Show("Shift Timing Has Been Updated.");
}
}

Delete selected rows from DataGridView and Database

I want to delete the selected rows from DataGridView and this delete should affect the database. I'm using the Entity Framework and that is my code which did not work.
private void button4_Click(object sender, EventArgs e)
{
var toBeDeleted = (int)dataGridView1.SelectedRows[0].Cells[0].Value;
var TE = new TaskEntities();
var UD = new userdata();
UD = TE.userdatas.First(c => c.ID == toBeDeleted);
TE.DeleteObject(UD);
TE.SaveChanges();
}
Is your DGV bound to any dataSource?
Is so, delete row from datasource, and then do use Update command (or update sql query) to do chnages in database.
try this:
private void button4_Click(object sender, EventArgs e)
{
var toBeDeleted = (int)dataGridView1.SelectedRows[0].Cells[0].Value;
var TE = new TaskEntities();
var userdata = TE.userdatas.First(c => c.ID == toBeDeleted);
TE.userdatas.Remove(userdata);
TE.SaveChanges();
dataGridView1.DataSource = TE.userdatas;
}

Categories

Resources