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();
}
Related
the SS of my current App
I set all the codes to retrieve the information from the SQL table , now i only need to convert the retrieved image URL to Image in the DataGridView
here is the codes am using now :
namespace LamasoDemo
{
public partial class FormOrders : Form
{
public FormOrders()
{
InitializeComponent();
FillGridView();
}
void FillGridView()
{
List<Products> productsList = new List<Products>();
Products products = new Products();
productsList = products.GetProducts();
dataGridViewProducts.DataSource = productsList;
}
and on the class here is the codes :
public class Products
{
public string? Image { get; set; }
string connectionString = "Data Source=AHMEDBABAJAN;Initial Catalog=Lamaso1;Integrated Security=True;Trust Server Certificate=true";
public List<Products> GetProducts()
{
List<Products> ProductsList = new List<Products>();
SqlConnection con = new SqlConnection(connectionString);
string selectSQL = "select Image Status From GetProductsData";
con.Open();
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr != null)
{
while (dr.Read())
{
Products Products = new Products();
Products.Image = dr["Image"].ToString();
ProductsList.Add(Products);
}
}
return ProductsList;
}
Anyone have any idea on how to show the image ? from URL
The easiest solution is using an unbound DataGridViewImageColumn, then you can handle CellFormatting event and load the image.
In the following example, I've handled the CellFormatting event, considering the following points:
The code loads images lazily, once requested in CellFormattings.
It stores image in the cell value, to avoid loading it again.
To try the code, create a Form, drop a DataGridView on it and use the following code:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
httpClient.DefaultRequestHeaders.TryAddWithoutValidation(
"User-Agent", "Mozilla/5.0 (Windows NT 6.2; " +
"WOW64; rv:19.0) Gecko/20100101 Firefox/19.0");
//Load data
var data = GetData();
//Set up dataGridView
dgv1.RowTemplate.Height = 100;
dgv1.DataSource = data;
dgv1.Columns.Add(new DataGridViewImageColumn()
{
Name = "ImageColumn",
HeaderText = "Image",
ImageLayout = DataGridViewImageCellLayout.Zoom,
Width = 150
});
dgv1.CellFormatting += dgv1_CellFormatting;
}
private async void dgv1_CellFormatting(object sender,
DataGridViewCellFormattingEventArgs e)
{
if (e.RowIndex >= 0 && e.RowIndex < dgv1.NewRowIndex &&
dgv1.Columns[e.ColumnIndex].Name == "ImageColumn")
{
var item = (DataRowView)dgv1.Rows[e.RowIndex].DataBoundItem;
var uri = item.Row.Field<string>("ImageUri");
if (e.Value == null || e.Value == DBNull.Value)
{
dgv1.Rows[e.RowIndex]
.Cells["ImageColumn"].Value = await DownloadImage(uri);
}
}
}
DataTable GetData()
{
var data = new DataTable();
data.Columns.Add("Name", typeof(string));
data.Columns.Add("ImageUri", typeof(string));
data.Rows.Add("Lorem", $"https://picsum.photos/300/200?1");
data.Rows.Add("Ipsum", $"https://picsum.photos/300/200?2");
data.Rows.Add("Dolor", $"https://picsum.photos/300/200?3");
data.Rows.Add("Sit", $"https://picsum.photos/300/200?4");
data.Rows.Add("Amet", $"https://picsum.photos/300/200?5");
return data;
}
HttpClient httpClient = new HttpClient();
async Task<Image> DownloadImage(string uri)
{
return Image.FromStream(await httpClient.GetStreamAsync(uri));
}
Run the code and see the result.
You should also take care of disposing the images:
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
if (!e.Cancel)
{
DisposeImages();
}
}
void DisposeImages()
{
foreach (DataGridViewRow row in dgv1.Rows)
{
if (!row.IsNewRow)
{
var value = row.Cells["ImageColumn"].Value;
row.Cells["ImageColumn"].Value = null;
if (value is Image)
((Image)value).Dispose();
}
}
}
You may also want to modify the code and handle cases when the image could not be downloaded.
I m working on a shopping cart like Form in WF. I have a DataGridView an ADD_Button and Submit_Button.The user will choose Items From inventory and Click ADD_ButtonThe item will go into DataGridView After Finishing User will click Submit_Button then detail will go into DB.
Question: is this After adding a product/row into DatagridView When I add same product again.it goes into the new row I want that Where Pro_ID Column Match, The row update with new qty. I tried to search the web but all I got SQL queries.
private void btn_Add_Click(object sender, EventArgs e)
{
i = dgv_Purchase.Rows.Count;
try
{
dgv_Purchase.Rows.Add();
.......
.......
dgv_Purchase.Rows[i - 1].Cells["Pro_ID"].Value = txt_ProID.Text;
.......
.......
dgv_Purchase.Rows[i - 1].Cells["Purchase_Qty"].Value = txt_Qty.Text;
}
catch (Exception ){}
}
This is Submit Button Code
private void btnInsert_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["PRMSConnectionString"].ToString();
SqlConnection con = new SqlConnection(cs);
SqlTransaction objTransaction;
for (int i = 0; i < dgv_Purchase.Rows.Count - 1; i++)
{
//SomeCode part of code
SqlCommand objCmd2;
string cmd2 = "INSERT INTO PurchaseMaster " +
" (Pro_ID , category_ID, Purchase_Qty) " +
"VALUES (#Pro_ID, #category_ID, #Purchase_Qty)";
objCmd2 = new SqlCommand(cmd2, con, objTransaction);
objCmd2.Parameters.AddWithValue("#Pro_ID_ID", dgv_Purchase.Rows[i].Cells["Pro_ID"].Value.ToString());
objCmd2.Parameters.AddWithValue("#Category_ID", dgv_Purchase.Rows[i].Cells["Category_ID"].Value.ToString());
objCmd2.Parameters.AddWithValue("#Purchase_Qty", Convert.ToInt32(dgv_Purchase.Rows[i].Cells["Purchase_Qty"].Value.ToString()));
objCmd2.Parameters.AddWithValue("#Date_Today", Convert.ToDateTime(dgv_Purchase.Rows[i].Cells["Purchase_Date"].Value.ToString()));
...........................
Rest of the Code
...........................
try
{
objCmd2.ExecuteNonQuery();
objTransaction.Commit();
}
catch (Exception) {}
}
}
Try this:
private void AddInfo()
{
// flag so we know if there was one dupe
bool updated = false;
// go through every row
foreach (DataGridViewRow row in dgv_Purchase.Rows)
{
// check if there already is a row with the same id
if (row.Cells["Pro_ID"].ToString() == txt_ProID.Text)
{
// update your row
row.Cells["Purchase_Qty"] = txt_Qty.Text;
updated = true;
break; // no need to go any further
}
}
// if not found, so it's a new one
if (!updated)
{
int index = dgv_Purchase.Rows.Add();
dgv_Purchase.Rows[index].Cells["Purchase_Qty"].Value = txt_Qty.Text;
}
}
I edit it with a DGVrow instead of DataRow
foreach (DataGridViewRow dr in dataGridView1.Rows)
{
if (dr.Cells["Pro_ID"].Value.ToString() == txt_ProID.Text)
{
dr.Cells["Purchase_Qty"].Value = txt_Qty.Text;
}
}
Im facing a very weird issue, wich should be very simple.
What im trying to achieve: I have 2 datagrids: 1 with invoiceheaders and 1 with invoiceDetails.
When i click on a particular row from the invoiceheaders, the invoicedetails need to change and show the particular details of that invoice. The event im using for this is dgvInvoiceHeaders_SelectionChanged.
So the code in the view:
private void InvoiceListView_Load(object sender, EventArgs e)
{
int invoiceId = 1;
invoiceHeadersBinding.DataSource = invoiceListPresenter.getInvoiceHeaders();
dgvInvoiceHeaders.DataSource = invoiceHeadersBinding;
setInvoiceHeaderColumns();
if (dgvInvoiceHeaders.CurrentRow != null)
{
Int32.TryParse(dgvInvoiceHeaders.CurrentRow.Cells[0].FormattedValue.ToString(), out invoiceId);
}
dgvInvoiceDetails.DataSource = invoiceListPresenter.getSelectedInvoiceDetails(invoiceId);
dgvInvoiceDetails.DataSource = invoiceListPresenter.invoiceDetails;
setInvoiceDetailColumns();
}
private void dgvInvoiceHeaders_SelectionChanged(object sender, EventArgs e)
{
dgvInvoiceDetails.DataSource = invoiceListPresenter.getSelectedInvoiceDetails(Convert.ToInt32(dgvInvoiceHeaders.CurrentRow.Cells[0].FormattedValue.ToString()));
dgvInvoiceDetails.DataSource = invoiceListPresenter.invoiceDetails;
setInvoiceDetailColumns();
}
And this is the code of the methods im calling:
public List<tbl_invoices> invoiceHeaders;
public BindingList<tbl_invoices> getInvoiceHeaders()
{
try
{
using (var invoices = new DBCrownfishEntities())
{
invoices.Configuration.LazyLoadingEnabled = false;
var invoice = from i in invoices.tbl_invoices
select i;
invoiceHeaders = invoice.ToList();
var listBinding = new BindingList<tbl_invoices>(invoiceHeaders);
return listBinding;
}
}
catch (Exception exe)
{
throw exe;
}
}
public List<tbl_invoiceDetail> invoiceDetails;
public BindingList<tbl_invoiceDetail> getSelectedInvoiceDetails(int invoiceID)
{
try
{
using (var invoices = new DBCrownfishEntities())
{
invoices.Configuration.LazyLoadingEnabled = false;
var invoiceDetail = from i in invoices.tbl_invoiceDetail
where i.InvoiceID == invoiceID
select i;
invoiceDetails = invoiceDetail.ToList();
var listBinding = new BindingList<tbl_invoiceDetail>(invoiceDetails);
return listBinding;
}
}
catch (Exception exe)
{
throw exe;
}
}
But with this example the formload is loaded correctly. But after the event is fired, my invoiceheader datagrid is empty. When i put the text in comment at the method dgvInvoiceHeaders_selectionChanged(), I see that both of the datagrids are filled correctly.
A push in the right direction would be very kind.
I want to update an existing record. I also have debugged my code. The int id variable gets the value, but I don't know why my record doesn't updated.
SQLDBDataClassesDataContext dContext = new SQLDBDataClassesDataContext();
protected void Page_Load(object sender, EventArgs e)
{
//if (!IsPostBack)
{
if (!string.IsNullOrEmpty(Request.QueryString["fname"]))
{
FirstNameTextBox.Text = Request.QueryString["fname"];
}
if (!string.IsNullOrEmpty(Request.QueryString["lname"]))
{
LastNameTextBox.Text = Request.QueryString["lname"];
}
if (!string.IsNullOrEmpty(Request.QueryString["cellnum"]))
{
CellNumberTextBox.Text = Request.QueryString["cellnum"];
}
}
}
protected void UpdateButton_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(Request.QueryString["id"]);
var updatequery1 = dContext.PersonalDetailTables
.Where(pd => pd.ID == id).SingleOrDefault();
if (updatequery1 != null)
{
updatequery1.FirstName = FirstNameTextBox.Text;
updatequery1.LastName = LastNameTextBox.Text;
updatequery1.CellNumber = CellNumberTextBox.Text;
dContext.SubmitChanges();
}
}
if (updatequery1 != null)
is updatequery1 null? If it's now, it'll just skip right over. Setup a breakpoint and step through.
Alternatively, change .SingleOrDefautl to .Single instead. This way if nothing's found, u'll get an exception, and u'll know what's up.
Call dContext.InsertOnSubmit(fooentity) method before calling dContext.SubmitChanges();.
For example.
var ctx = DB.fooDB;
fooobj.fooName= bar.fooName;
fooobj.fooID= bar.fooID;
if (fooobj.fooID== 0)
ctx.Locations.InsertOnSubmit(bar);
ctx.SubmitChanges();
I`ve got my Solution..
the only problem was of if(!ispostback) issue.
context.InvProductStockMasters
.Update(ps => ps.LocationID.Equals(invStockAdjustmentHeader.LocationID)
&& ps.ProductID.Equals(invStockAdjustmentDetail.ProductID),
ps => new InvProductStockMaster
{ Stock = ps.Stock - invStockAdjustmentDetail.OrderQty });
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