Delete row from gridview and also remove item from binding - c#

I have a GridView filled in using an object this way:
Ingreso I = new Ingreso();
I.ID_Producto = ID_Producto;
I.Producto = cmb_producto.Text;
I.ID_Productor = ID_Productor;
I.Productor = cmb_productor.Text;
I.Fecha_Ingreso = Fecha.Value.Date;
I.Cantidad = Convert.ToInt16(txt_cantidad_ingresada.Text);
I.Precio_Unitario = Convert.ToDecimal(txt_precio_unitario.Text);
I.Descripcion = txt_descripcion.Text;
Ingresos.Add(I);
ListadeIngresos = new BindingList<Ingreso>(Ingresos);
BindingSource source = new BindingSource(ListadeIngresos, null);
Grid_Ingreso.DataSource = source;
Then user needs to delete a row that was added, I'm trying this way:
private void Grid_Ingreso_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
int index = e.Row.Index;
Ingresos.RemoveAt(index);
ListadeIngresos.RemoveAt(index);
BindingSource source = new BindingSource(ListadeIngresos, null);
Grid_Ingreso.DataSource = source;
}
My problem is that the row gets deleted three times from the gridview and the object (Ingresos). It's like the event firing 3 times, but when I debug I only see it entering once. Why this is happening?
Thanks

Related

Populate combobox inside DataGridView with the values of List

I am trying to add a Combobox inside a DataGridView the method where I am managing this is repeated plenty of times if I refresh another combobox that I have in Windows form, I run this method all over again
this.DataGridView1.ColumnCount = Constants.Vacation_Calendar.Total_Calendar_Days + 2;
this.DataGridView1.Columns[0].Name = "Resource";
this.DataGridView1.Columns[0].Width = 100;
this.DataGridView1.Columns[1].Name = "Month";
this.DataGridView1.Columns[1].Width = 60;
DataGridViewComboBoxColumn cb = new DataGridViewComboBoxColumn();
List<Process> getAllProcesses = this.bl_process.getAll_Process();
List<String> getApplication= new List<string>();
foreach (Process process in getAllProcesses)
{
getApplication.Add(process.Application);
}
if (!DataGridView1.Columns.Cast<DataGridViewColumn>().Any(x => x.Name == "ProcessColumn"))
{
cb.HeaderText = "Process";
cb.Name = "ProcessColumn";
cb.Width = 100;
cb.DataSource = getApplication;
cb.ReadOnly = false;
DataGridView1.Columns.Insert(2, cb);
}
I keep getting an Error that I handled with the following code in the designer:
this.DataGridView1.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(this.DataGridView1_DataError);
And in code behind:
private void DataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e){}
with all this I can't see my list populating the combobox, what's still missing here?
Thank you so much in advance
PS: I added "getApplication" object to the Quickwatches and it's receiving all the values from my List, so it's all good.
don't i need something like a method SelectedIndexChanged bounded to my combobox inside gridview? to see what i am selecting

Trouble Getting DataGridView to Work with ComboBox Dropdown

I need some help getting my code to work. DataGridView is proving much more complex that I had anticipated. I need someone to please show me how to fix my code, so that both the DataGridView control can be updated and my DataGridViewComboBoxColumn dropdown and DataGridViewCheckBoxColumn controls all work. I'm okay with any strategy, provided the solution you offer is somewhat elegant and complete. I've already spent far too much time trying to figure this out on my own. Any thoughts or suggestions would be greatly appreciated.
Here is a simplifcation of what my backend looks like:
MySqlDataAdapter dataAdapter = new MySqlDataAdapter(sqlRequestString, this.dbConnection);
MySqlCommandBuilder commandBuilder = new MySqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource.DataSource = table;
If I get rid of the BindingSource, how do I connect the DataTable directly to the DataGridView, so that the ComboBox and Checkbox columns are properly populated?
UPDATE
This should be a complete overview of how I am attempting to initialize my DataGridView:
private void InitializeComponent()
{
/* ... */
this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.DataGridViewColumn_Section,
this.DataGridViewColumn_Indent,
this.DataGridViewColumn_Content,
this.DataGridViewColumn_Summary,
this.DataGridViewColumn_Role,
this.DataGridViewColumn_Author,
this.DataGridViewColumn_Updated});
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.DataSourceChanged += new System.EventHandler(this.dataGridView1_DataSourceChanged);
this.dataGridView1.CellEnter += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellEnter);
this.dataGridView1.CellLeave += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellLeave);
this.dataGridView1.ColumnAdded += new System.Windows.Forms.DataGridViewColumnEventHandler(this.dataGridView1_ColumnAdded);
this.dataGridView1.SelectionChanged += new System.EventHandler(this.dataGridView1_SelectionChanged);
this.dataGridView1.Leave += new System.EventHandler(this.dataGridView1_Leave);
//
// DataGridViewColumn_Section
//
this.DataGridViewColumn_Section.HeaderText = "Section";
this.DataGridViewColumn_Section.Name = "DataGridViewColumn_Section";
//
// DataGridViewColumn_Indent
//
this.DataGridViewColumn_Indent.HeaderText = "Indent";
this.DataGridViewColumn_Indent.Name = "DataGridViewColumn_Indent";
//
// DataGridViewColumn_Content
//
this.DataGridViewColumn_Content.HeaderText = "Content";
this.DataGridViewColumn_Content.MinimumWidth = 100;
this.DataGridViewColumn_Content.Name = "DataGridViewColumn_Content";
//
// DataGridViewColumn_Summary
//
this.DataGridViewColumn_Summary.HeaderText = "Summary";
this.DataGridViewColumn_Summary.Name = "DataGridViewColumn_Summary";
//
// DataGridViewColumn_Role
//
this.DataGridViewColumn_Role.HeaderText = "Minimum Signoff";
this.DataGridViewColumn_Role.Name = "DataGridViewColumn_Role";
//
// DataGridViewColumn_Author
//
this.DataGridViewColumn_Author.HeaderText = "Author";
this.DataGridViewColumn_Author.Name = "DataGridViewColumn_Author";
this.DataGridViewColumn_Author.ReadOnly = true;
//
// DataGridViewColumn_Updated
//
this.DataGridViewColumn_Updated.HeaderText = "Updated";
this.DataGridViewColumn_Updated.Name = "DataGridViewColumn_Updated";
this.DataGridViewColumn_Updated.ReadOnly = true;
/* ... */
}
public MyWinform()
{
InitializeComponent();
// Initialize DataGridView DataTable
this.dgvDataTable = new DataTable();
// Initialize DataGridView column indexes
this.idxSection = dataGridView1.Columns["DataGridViewColumn_Section"].Index;
this.idxIndent = dataGridView1.Columns["DataGridViewColumn_Indent"].Index;
this.idxContent = dataGridView1.Columns["DataGridViewColumn_Content"].Index;
this.idxSummary = dataGridView1.Columns["DataGridViewColumn_Summary"].Index;
this.idxRole = dataGridView1.Columns["DataGridViewColumn_Role"].Index;
this.idxAuthor = dataGridView1.Columns["DataGridViewColumn_Author"].Index;
this.idxLastUpdate = dataGridView1.Columns["DataGridViewColumn_Updated"].Index;
}
private void MyWinform_Load(object sender, EventArgs e)
{
DataGridView dgv = this.dataGridView1;
DataGridViewComboBoxColumn comboCol;
// Load System Menu
SystemMenu.Load(this.Handle);
// Insert selection prompt
ProcTemplateRecord selectProcPrompt = new ProcTemplateRecord();
selectProcPrompt.PrimaryKey = 0;
selectProcPrompt.ProcName = "Select from the list...";
this.procList.Insert(0, selectProcPrompt);
// Add new procedure prompt
ProcTemplateRecord newProcPrompt = new ProcTemplateRecord();
newProcPrompt.PrimaryKey = -1;
newProcPrompt.ProcName = "Start a new Safe Job Procedure";
this.procList.Add(newProcPrompt);
// Finish initializing the ComboBox dropdown list
this.comboBox1.DataSource = this.procList;
this.comboBox1.DisplayMember = "ProcName";
this.comboBox1.ValueMember = "PrimaryKey";
// Finish initializing DataGridView and bind to BindingSource
this.dataGridView1.AutoGenerateColumns = false;
/*
// Finish initializing the DataGridView ComboBox columns...
comboCol = (DataGridViewComboBoxColumn)dgv.Columns[this.idxSection];
comboCol.DataSource = Enum.GetValues(typeof(SectionType));
comboCol.ValueType = typeof(SectionType);
comboCol.DropDownWidth = ComboBoxMaxLabelWidth(comboCol);
comboCol = (DataGridViewComboBoxColumn)dgv.Columns[this.idxRole];
comboCol.DataSource = Enum.GetValues(typeof(RoleType));
comboCol.ValueType = typeof(RoleType);
comboCol.DropDownWidth = ComboBoxMaxLabelWidth(comboCol);
this.dataGridView1.DataSource = this.dgvDataTable;
*/
this.RefreshDataGridViewColumnWidths();
// Setup post-initialization DataGridViewEvent handlers
this.dataGridView1.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellValueChanged);
this.dataGridView1.CurrentCellDirtyStateChanged += new System.EventHandler(this.dataGridView1_CurrentCellDirtyStateChanged);
}
private void dataGridView1_DataSourceChanged(object sender, EventArgs e)
{
this.RefreshDataGridViewColumnWidths();
}
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
this.RefreshButtons();
if (e.ColumnIndex == this.idxSection)
{
this.label_dgvToolTip.Visible = false;
}
else if (e.ColumnIndex == this.idxIndent)
{
this.label_dgvToolTip.Visible = false;
}
else if (e.ColumnIndex == this.idxContent)
{
this.label_dgvToolTip.Visible = false;
}
else if (e.ColumnIndex == this.idxSummary)
{
this.label_dgvToolTip.Visible = false;
}
else if (e.ColumnIndex == this.idxRole)
{
this.label_dgvToolTip.Visible = false;
}
else if (e.ColumnIndex == this.idxAuthor)
{
this.label_dgvToolTip.Visible = false;
this.label_dgvToolTip.Text = "Author column values are read only.";
this.label_dgvToolTip.Visible = true;
}
else if (e.ColumnIndex == this.idxLastUpdate)
{
this.label_dgvToolTip.Visible = false;
this.label_dgvToolTip.Text = "Updated column values are read only.";
this.label_dgvToolTip.Visible = true;
}
else
{
this.label_dgvToolTip.Visible = false;
}
this.idxActiveColumn = e.ColumnIndex;
this.idxActiveRow = e.RowIndex;
}
private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e)
{
this.label_dgvToolTip.Visible = false;
this.RefreshButtons();
}
private void dataGridView1_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
{
DataGridView dgv = this.dataGridView1;
if ((e.Column.DataPropertyName == "PageSection") &&
(e.Column.CellType != typeof(DataGridViewComboBoxCell)))
{
var cbo = GetComboBoxColumn(e.Column);
cbo.DataSource = Enum.GetValues(typeof(SectionType));
cbo.ValueType = typeof(SectionType);
dgv.Columns.Remove(e.Column);
dgv.Columns.Add(cbo);
}
else if ((e.Column.DataPropertyName == "UserRole") &&
(e.Column.CellType != typeof(DataGridViewComboBoxCell)))
{
var cbo = GetComboBoxColumn(e.Column);
cbo.DataSource = Enum.GetValues(typeof(RoleType));
cbo.ValueType = typeof(RoleType);
dgv.Columns.Remove(e.Column);
dgv.Columns.Add(cbo);
}
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
this.RefreshButtons();
}
private void dataGridView1_Leave(object sender, EventArgs e)
{
DataGridView dgv = this.dataGridView1;
if (dgv.SelectedCells.Count == 0)
{
this.idxActiveColumn = -1;
this.idxActiveRow = -1;
}
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
DataGridViewComboBoxCell sectionCell = (DataGridViewComboBoxCell)dgv.Rows[e.RowIndex].Cells[this.idxSection];
DataGridViewTextBoxCell indentCell = (DataGridViewTextBoxCell)dgv.Rows[e.RowIndex].Cells[this.idxIndent];
DataGridViewComboBoxCell roleCell = (DataGridViewComboBoxCell)dgv.Rows[e.RowIndex].Cells[this.idxRole];
Int32 colIndex = e.ColumnIndex;
try
{
if (colIndex == this.idxIndent)
{
int number;
string cellValue = indentCell.Value.ToString();
bool isNumeric = int.TryParse(cellValue, out number);
if (!isNumeric)
{
cellValue = cellValue.Substring(0, cellValue.Length - 1);
indentCell.Value = cellValue;
}
}
// Column resizing code goes last
this.RefreshDataGridViewColumnWidths();
this.dgvIsDirty = true;
}
catch (Exception ex)
{
throw new Exception("Failed to refresh DataGridView on cell change.", ex);
}
}
private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
DataGridView dgv = (DataGridView)sender;
try
{
if (dgv.IsCurrentCellDirty)
{
// This fires the cell value changed handler below
dgv.CommitEdit(DataGridViewDataErrorContexts.Commit);
this.RefreshDataGridViewColumnWidths();
}
}
catch (Exception ex)
{
throw new Exception("Failed to commit edit of DataGridView cell.", ex);
}
}
This is the code I am using to update my DataGridView contorl:
// Load the data from the database into the DataGridView
this.dbif.GetProcedure(this.procList.ElementAt(selectedIndex).PrimaryKey, ref this.dgvDataTable);
DataRow[] rows = this.dgvDataTable.Select();
//Object dgvDataSource = dgv.DataSource;
//dgv.DataSource = null;
foreach (DataRow dataRow in rows)
{
DataGridViewRow dgvRow = new DataGridViewRow();
dgvRow.CreateCells(dgv);
dgvRow.Cells[idxSection].Value = dataRow.Field<string>(0);
dgvRow.Cells[idxIndent].Value = dataRow.Field<byte>(1);
dgvRow.Cells[idxContent].Value = dataRow.Field<string>(3);
dgvRow.Cells[idxSummary].Value = dataRow.Field<UInt32>(4) != 0;
dgvRow.Cells[idxRole].Value = dataRow.Field<string>(5);
dgvRow.Cells[idxAuthor].Value = dataRow.Field<string>(6) + dataRow.Field<string>(7);
dgvRow.Cells[idxLastUpdate].Value = dataRow.Field<DateTime>(8).ToString();
dgv.Rows.Add(dgvRow);
}
//dgv.DataSource = dgvDataSource;
This is how my enumerations are defined:
public enum SectionType
{
ESJP_SECTION_HEADER = 1, // start with 1 for database compatibility
ESJP_SECTION_FOOTER,
ESJP_SECTION_BODY
}
public enum RoleType
{
ESJP_ROLE_NONE = 1, // start with 1 for database compatibility
ESJP_ROLE_TEST_ENG,
ESJP_ROLE_FEATURE_LEAD,
ESJP_ROLE_TEAM_LEAD
}
There are a number of issues/improvements. There are too many unknowns about the data to fix everything, but some techniques shown here may help.
1. Manually populating the DGV
You ought not have to do that. Just setting the DataTable as the DataSource will work most of the columns.
2. Expressions
You have 2 expressions where you populate the dgv:
dgvRow.Cells[idxSummary].Value = dataRow.Field<UInt32>(4) != 0;
dgvRow.Cells[idxAuthor].Value = dataRow.Field<string>(6) + dataRow.Field<string>(7);
This leads me to believe the dgv is ReadOnly. Otherwise you will have trouble with those. The Summary for instance: if the user Unchecks the column, you can set that value to 0, but what if they check it? How will you know what value to set??
Indent as Byte seems odd too - almost like it is a boolean.
3. Combos
In a previous question, the dgv was populated from a List<Class>. With that as the `DataSource, an Enum works well because the 2 properties were of that Type. With an enum, the following works:
cbo.ValueType = typeof(RoleType);
It's less likely to work with a DataTable as in version 1, 2 or 3 of this question because there is no db/Datatable type of SectionType or RoleType. In other cases where there is a translation - show the user "ESJP_SECTION_HEADER" but store 2 in the DataTable and ultimately the DB - a small NameValue pairs list will work. A different data model means a different approach to the DGV cbo.
It now looks like those are text columns (I've asked 3 times). If so, you really just need to constrain the selection to the enum names. In the IDE, paste in the text for the Items property:
Alternatively, you can do so in code:
private string[] secList = {"ESJP_SECTION_HEADER","ESJP_SECTION_FOOTER",
"ESJP_SECTION_BODY"};
...
((DataGridViewComboBoxColumn)dgv1.Columns["PageSection"]).Items.AddRange(secList);
AutoGenerateColumns
When the DataSource for a DGV is set, by default it will automatically create a DGVcolumn for each DTColumn, and this works well for the most part. Sometimes you'll want some small tweak like hide an Id column, or change a TextColumn to a CBOColumn. Code in the ColumnAddedEvent to make these changes rather than manually laying out columns can work well.
But since there are quite a few such such changes and since you have already layed out columns in the IDE, you want to be sure to set AutoGenerateColumns to false somewhere in code. Otherwise it will add still more columns.
Setup
Things you may or may not have done in the DGV designer:
Add the columns in whatever order you wish, but be sure to assign the DataPropertyName to the name used in the SQL query. Leave it blank for Author.
Expression columns like Author means either changing the query or doing some formatting in the DGV. For this, add First and Last name columns to the DGV as well as the Author column. Make the first two invisible. The code below shows the formatting. (Make sure that the compound column (Author) appears after the parts!).
Normally, I would try to do that in SQL: SELECT (First + Last) AS Author, but if you do not want to mess with that query, you can concat in DGV events.
Be sure to add the names for the Page and Role columns to the Items collection.
Then, the rest is fairly simple:
private DataTable dtF;
...
string SQL = "SELECT PageSection, Indent, Content, SummaryId, "
+ "UserRole, AuthorFirstN, AuthorLastN, LastUpdated FROM FellPage";
using (var dbCon = new MySqlConnection(MySQLConnStr))
using (var cmd = new MySqlCommand(SQL, dbCon))
{
dbCon.Open();
dtF = new DataTable();
dtF.Load(cmd.ExecuteReader());
}
// IMPORTANT!!!
dgv1.AutoGenerateColumns = false;
dgv1.DataSource = dtF;
The formatting event:
private void dgv1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dgv1.Rows[e.RowIndex].IsNewRow)
return;
if (e.ColumnIndex == 7) // ie "Author"
{
e.Value = dgv1.Rows[e.RowIndex].Cells[6].Value.ToString() + ", " +
dgv1.Rows[e.RowIndex].Cells[5].Value.ToString();
e.FormattingApplied = true;
}
}
Result:
It is very important to turn off AutoGenerateColumns. By default, the dgv will add columns for everything in the source. Since you added them, set that to false in the code (there is no IDE property for it).
By virtue of Summary and Indent being defined as check columns, it translates non zero as true. I have no idea how you will edit any SummaryId value. That should probably be a text column so they can enter a value, if that is allowed (that col could be read only too?).
My query and such arent as complex as yours, and surely there are some details I/we are unaware of which have been omitted. But there is certainly a much less gyrations and code to get it working...whatever this is.
Being bound to a DataTable, when the user edits anything, the changes flow thru to the underlying DataTable (use the various Validating events to check their work). The DataTable in turn tracks the state of each row - new, changed, deleted - so later you can:
var changes = dtF.GetChanges();
This will return all the rows which have been changed since the last AcceptChanges().

Delete row in DataGridView and database

I'm completely new to databases and EF but I made a database with EF and have a DataGridView control on a windows form that I made by dragging my datasource to my form. After the user enters their information and hits the save button it succesfully saves their information in the database using this code
public partial class bsMainPage : Form
{
BSDATAContainer db = new BSDATAContainer();
public bsMainPage()
{
InitializeComponent();
}
private void saveBtn_Click(object sender, EventArgs e)
{
BSRecords breakfastRecord = new BSRecords();
breakfastRecord.BS = brkBS.ToString();
breakfastRecord.Carbs = brkCarb.ToString();
breakfastRecord.Notes = brkftNoteTxt.Text;
breakfastRecord.Date = dateTxt.Text;
BSRecords lunchRecord = new BSRecords();
lunchRecord.BS = lchBS.ToString();
lunchRecord.Carbs = lchCarb.ToString();
lunchRecord.Notes = lnchNoteTxt.Text;
lunchRecord.Date = dateTxt.Text;
BSRecords dinnerRecord = new BSRecords();
dinnerRecord.BS = dnrBS.ToString();
dinnerRecord.Carbs = dnrCarb.ToString();
dinnerRecord.Notes = dnnrNoteTxt.Text;
dinnerRecord.Date = dateTxt.Text;
db.BSRecords.Add(breakfastRecord);
db.BSRecords.Add(lunchRecord);
db.BSRecords.Add(dinnerRecord);
db.SaveChanges();
}
}
But it doesn't show up in the database until I restart the program. When the user selects a row in the DataGridView and hits the delete button which has this code
private void deleteRowsBtn_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow item in this.bSRecordsDataGridView.SelectedRows)
{
bSRecordsDataGridView.Rows.RemoveAt(item.Index);
}
db.SaveChanges();
}
It deletes the data in the DataGridView but doesn't save the changes in my database. I have followed all the answers I found on here and other sites to delete in the database but nothing will save the deleted changes. Does anyone have any idea how to make it work?
You can delete it using remove. You will need to get the key/id field so without seeing the grid and assuming it is say in a hidden first column:
private void deleteRowsBtn_Click(object sender, EventArgs e)
{
string delId;
BSRecords deleteRecord;
foreach (DataGridViewRow item in this.bSRecordsDataGridView.SelectedRows)
{
bSRecordsDataGridView.Rows.RemoveAt(item.Index);
// code to remove record from database
delId = item.Cells[0].Value.ToString(); // column that has id field
deleteRecord = db.BSRecords.First(b => b.Id == delId); // get the record. will throw exception if not found.
db.BSRecords.Remove(deleteRecord);
}
db.SaveChanges();
bSRecordsDataGridView.DataBind(); // this will refresh your grid. Do same in save.
}
Also note you can rewrite this code:
BSRecords breakfastRecord = new BSRecords();
breakfastRecord.BS = brkBS.ToString();
breakfastRecord.Carbs = brkCarb.ToString();
breakfastRecord.Notes = brkftNoteTxt.Text;
breakfastRecord.Date = dateTxt.Text;
with an object initializer:
BSRecords breakfastRecord = new BSRecords { BS = brkBS.ToString(),
Carbs = brkCarb.ToString(),
Notes = brkftNoteTxt.Text,
Date = dateTxt.Text };

I need to get the value of a drop down list in an asp gridview when updating the row

Everything should work, but i can't figure out why i can't get the value from the ddl. I know the code is not too clean.
protected void gridProduse_RowEditing(object sender, GridViewEditEventArgs e)
{
gridProduse.EditIndex = e.NewEditIndex;
gridProduse.DataBind();
using (var context = new SATContext())
{
var query = from t in context.TipuriProduse
select t.Denumire;
DropDownList list = new DropDownList();
list.DataSource = query.ToList();
list.DataBind();
list.ID = "ddlTipProdus";
list.Height = 27;
DropDownList listMoneda = new DropDownList();
listMoneda.ID = "ddlMoneda";
listMoneda.Items.Add("RON");
listMoneda.Items.Add("EUR");
listMoneda.Items.Add("USD");
listMoneda.Height = 27;
gridProduse.Rows[e.NewEditIndex].Cells[7].Controls.Add(list);
gridProduse.Rows[e.NewEditIndex].Cells[6].Controls.Add(listMoneda);
gridProduse.Rows[e.NewEditIndex].Cells[6].Controls[0].Visible = false;
gridProduse.Rows[e.NewEditIndex].Cells[7].Controls[0].Visible = false;
}
}
protected void gridProduse_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gridProduse.Rows[e.RowIndex];
Produs prod = new Produs();
prod.ProdusId = Convert.ToInt32(((TextBox)(row.Cells[2].Controls[0])).Text);
prod.Denumire = ((TextBox)(row.Cells[3].Controls[0])).Text;
DropDownList ddl = (DropDownList)gridProduse.Rows[e.RowIndex].FindControl("ddlMoneda");
prod.Moneda = ddl.SelectedValue; // this is where i get the error
//prod.Moneda = ((row.FindControl("ddlMoneda") as DropDownList)).SelectedValue;
prod.PretCuTVA = Convert.ToInt32(((TextBox)(row.Cells[5].Controls[0])).Text);
prod.PretFaraTVA = Convert.ToInt32 (((TextBox)(row.Cells[4].Controls[0])).Text);
lit1.Text = prod.ProdusId.ToString();
using (var context = new SATContext())
{
IRepository<Produs> ProdusRepository = new ProdusRepository();
ProdusRepository.Update(prod);
}
gridProduse.EditIndex = -1;
gridProduse.DataBind();
Response.Redirect("Produse.aspx");
}
And this is the error:
An exception of type 'System.NullReferenceException' occurred in Licenta.dll but was not handled in user code
Additional information: Object reference not set to an instance of an object.
I'm pretty sure that you need to select a cell before you can reliably call `FindControl'
(DropDownList)gridProduse.Rows[e.RowIndex].Cells[SomeCell].FindControl("ddlMoneda");
Since your listMoneda control is being created dynamically after the Page_Init event, it is not being registered in the ViewState, and thus cannot be found on PostBack. Read this explanation for a solution

Manual pagination:- next button

On Button click event I execute a new query i get a new table but i am unable to populate it on to the same grid view. Is there any why where i can use schema instead of dataTables.
private void GetData()//This method Displays the Datatable onto the Grid
{
int intCount = 0;
int.TryParse(txt_messagecount.Text, out intCount);
DataTable dtData = null;
//dtData = _objIMRSData.GetData(txt_fromdate.Text, txt_todata.Text, txt_messagecount.Text);
dtData = _objIMRSData.GetTransactionData( txt_fromdate.Text, txt_todata.Text,intCount );
grd_transactionLog.DataSource = dtData;
grd_transactionLog.DataBind();
dtData.Clear();
}
//On Button click event I execute a new query i get a new table
//but i am unable to populate it on to the same grid view
protected void btn_next_Click(object sender, EventArgs e)
{
int messageCount = int.Parse(txt_messagecount.Text);
string lastRecord = grd_transactionLog.Rows[messageCount-1].Cells[1].Text;
DataTable dtData1 = null;
//dtData = _objIMRSData.GetData(lastRecord, txt_todata.Text, txt_messagecount.Text);
dtData1 = _objIMRSData.GetTransactionData(lastRecord, txt_todata.Text, messageCount);
//grd_transactionLog.Columns.Clear();
grd_transactionLog.DataSource = dtData1;
grd_transactionLog.DataBind();
dtData1.Clear();
}
Reassign the datasource. In the click event do this.
grd_transactionLog.DataSource = null;
grd_transactionLog.DataSource = dtData1;

Categories

Resources