How to get cell value from dataTable Asp.Net - c#

I'm creating dynamically data table bound to Grid View. Every row is populated with button. When I determine which button is clicked on the row, I want to get the current value of cell in that row modify her.
Markup:
<asp:GridView ID="GridView2" runat="server"
OnRowDataBound="GridView2_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnTest" runat="server"
CommandName="odzemi"
CssClass="button2"
Font-Bold="True"
Text="-"
Width="100px"
OnClick="btnTest_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
Creating the row:
private void AddNewRecordRowToGrid()
{
int counter;
if (Request.Cookies["kasa"] == null)
counter = 0;
else
{
counter = int.Parse(Request.Cookies["kasa"].Value);
}
counter++;
Response.Cookies["kasa"].Value = counter.ToString();
Response.Cookies["kasa"].Expires = DateTime.Now.AddYears(2);
if (ViewState["Markici"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["Markici"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
HttpCookie cookie = Request.Cookies["Democookie"];
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["FirmaID"] = Request.Cookies["firma"].Value;
drCurrentRow["Godina"] = Request.Cookies["godina"].Value;
drCurrentRow["KasaID"] = Request.Cookies["kasa"].Value;
drCurrentRow["MarkicaID"] = Request.Cookies["kasa"].Value;
drCurrentRow["Datum"] = DateTime.Now;
drCurrentRow["Masa"] = Session["masa39"];
drCurrentRow["VrabotenID"] = Session["New"];
drCurrentRow["Artikal"] = Label3.Text;
drCurrentRow["Cena1"] = Label4.Text;
//this is where i need to make changes
drCurrentRow["Kolicina"] = Label5.text;
drCurrentRow["Smena"] = Session["smena1"];
drCurrentRow["VkIznos"] = Label6.Text;
drCurrentRow["VkDanok"] = Label8.Text;
drCurrentRow["SySDatum"] = DateTime.Now;
drCurrentRow["Vid"] = Label23.Text;
drCurrentRow["Edmera"] = Label10.Text;
drCurrentRow["ArtikalID"] = Label33.Text;
}
//Removing initial blank row
if (dtCurrentTable.Rows[0][0].ToString() == "")
{
dtCurrentTable.Rows[0].Delete();
dtCurrentTable.AcceptChanges();
}
//Added New Record to the DataTable
dtCurrentTable.Rows.InsertAt(drCurrentRow,0);
//storing DataTable to ViewState
ViewState["Markici"] = dtCurrentTable;
//binding Gridview with New Row
GridView2.DataSource = dtCurrentTable;
GridView2.DataBind();
}
}
}
//determine which button is clicked in data Table
//and here
protected void btnTest_Click(object sender, EventArgs e)
{
DataTable dtCurrentTable = (DataTable)ViewState["Markici"];
var clickedRow = ((Button)sender).NamingContainer as GridViewRow;
var clickedIndex = clickedRow.RowIndex;
count--;
decimal noofcount = count;
//and here i want to get current value and modify her.
dtCurrentTable.Rows[clickedIndex]["Kolicina"] = "88";
GridView2.DataSource = dtCurrentTable;
GridView2.DataBind();
}

If the only problem is that you don't know how to read the old value as noted here:
//and here i want to get current value and modify her.
dtCurrentTable.Rows[clickedIndex]["Kolicina"] = "88";
then this works:
object oldValue = dtCurrentTable.Rows[clickedIndex]["Kolicina"];
// cast/convert it to whatever it is
or (what i prefer):
string old = dtCurrentTable.Rows[clickedIndex].Field<string>("Kolicina");
int oldValue = int.Parse(old); // in case that you don't know
int newValue = oldValue + count; // just an example
dtCurrentTable.Rows[clickedIndex].SetField("Kolicina", newValue.ToString());
I'm using the Field/SetField extension methods for DataRow because it is strongly typed and even supports nullable types.
By the way, why do you store ints as strings?

Related

Can't get gridview dynamic label ID but textboxes are fine

Here is how i get the values from the gridview controllses, as you can see i do the same way for the label as the textbox, except all textboxes get value and label doesn't and i can't find anything different in the code. The function fillGrid() is just a skeleton for the table to fill it first before placing controllers on it
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
var Column1TextBoxes = Request.Form.AllKeys.Where(k => k.Contains("lblIdDetComp")).ToList(); // Gridview Column 1
var Column2TextBoxes = Request.Form.AllKeys.Where(k => k.Contains("txtComponente")).ToList(); // Gridview Column 2
var Column3TextBoxes = Request.Form.AllKeys.Where(k => k.Contains("txtBase")).ToList(); // Gridview Column 3
var Column4TextBoxes = Request.Form.AllKeys.Where(k => k.Contains("txtComprimento")).ToList(); // Gridview Column 4
if (Request.Form[Column1TextBoxes[j]] != "") comp[j].ID = Convert.ToInt32(Request.Form[Column1TextBoxes[j]]); // Column1 values
else break;
if (Request.Form[Column2TextBoxes[j]] != "") comp[j].Nome = Request.Form[Column2TextBoxes[j]]; // Column2 values
else break;
if (Request.Form[Column3TextBoxes[j]] != "") comp[j].Base = Request.Form[Column3TextBoxes[j]]; // Column3 values
else break;
if (Request.Form[Column4TextBoxes[j]] != "") comp[j].Comprimento = Convert.ToDouble(Request.Form[Column4TextBoxes[j]]); // Column4 values
else break;
j++;
}
}
private void fillGrid()
{
int rowCount = 0;
if (ViewState["rowCount"] != null)
{
rowCount = Convert.ToInt32(ViewState["rowCount"]);
}
DataTable dt = new DataTable();
dt.Columns.Add("IdDetComp",typeof(string));
dt.Columns.Add("Componente", typeof(string));
dt.Columns.Add("Base", typeof(string));
dt.Columns.Add("Comprimento", typeof(string));
for (int i = 0; i < rowCount; i++)
{
dt.Rows.Add("","", "", "");
}
GridView1.DataSource = dt;
GridView1.DataBind();
upDetComps.Update();
}
This is where I add the information to the gridview
int i = 0;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Visible = false;
if (e.Row.RowType == DataControlRowType.DataRow)
{
Componente[] Comp = (Componente[])ViewState["Componente"];
if (i < Convert.ToInt32(txtNumComps.Text))
{
Label lblIdDetComp = new Label();
lblIdDetComp.ID = "lblIdDetComp" + (i + 1).ToString();
if (Comp[i] != null) lblIdDetComp.Text = Comp[i].ID.ToString();
TextBox txtComponente = new TextBox();
txtComponente.ID = "txtComponente" + (i + 1).ToString();
if (Comp[i] != null) txtComponente.Text = Comp[i].Nome;
TextBox txtBase = new TextBox();
txtBase.ID = "txtBase" + (i + 1).ToString();
if (Comp[i] != null) txtBase.Text = Comp[i].Base;
TextBox txtComprimento = new TextBox();
txtComprimento.ID = "txtComprimento" + (i + 1).ToString();
if (Comp[i] != null)
{
if (Comp[i].Comprimento != 0)
txtComprimento.Text = Comp[i].Comprimento.ToString();
else
txtComprimento.Text = "";
}
e.Row.Cells[0].Controls.Add(lblIdDetComp);
e.Row.Cells[1].Controls.Add(txtComponente);
e.Row.Cells[2].Controls.Add(txtBase);
e.Row.Cells[3].Controls.Add(txtComprimento);
i++;
}
}
}
My guess would be this is because by default, the Label.AutoSize property is false:
Property Value
Boolean
true if the control adjusts its width to closely fit its contents; otherwise, false.
When added to a form using the designer, the default value is true. When instantiated from code, the default value is false.
So the text is there, it's just size (0,0).
Try setting
lblIdDetComp.AutoSize = true;

ASP.Net - Save previous Rows

I have a method which save previous data in DataTable rows. I want to click "Create" previous rows data be maintained.
private void SetOldData()
{
int rowIndex = 0;
if (ViewState["Curtbl"] != null)
{
DataTable dt = (DataTable)ViewState["Curtbl"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
TextBox txt1 = (TextBox)myGrid.Rows[rowIndex].Cells[0].FindControl("txt1");
DateTimeControl dt1 = (DateTimeControl)myGrid.Rows[rowIndex].Cells[1].FindControl("dt1");
DateTimeControl dt2 = (DateTimeControl)myGrid.Rows[rowIndex].Cells[2].FindControl("dt2");
TextBox txt2 = (TextBox)myGrid.Rows[rowIndex].Cells[3].FindControl("txt2");
TextBox txt3 = (TextBox)myGrid.Rows[rowIndex].Cells[4].FindControl("txt3");
txt1.Text = dt.Rows[i]["txt1"].ToString();
dt1.SelectedDate = dt.Rows[i]["dt1"];
dt2.SelectedDate = dt.Rows[i]["dt2"];
txt2.Text = dt.Rows[i]["txt2"].ToString();
txt3.Text = dt.Rows[i]["txt3"].ToString();
rowIndex++;
}
}
}
}
My problem is conversion between this dates :
dt1.SelectedDate = dt.Rows[i]["dt1"];
dt2.SelectedDate = dt.Rows[i]["dt2"];
Well, since SelectedDate most likely needs a Datetime and the the dt.Rows most likely returns a string, you have to parse it to a datetime:
DataTime dateValue;
if (Datetime.TryParse(dt.Rows[i]["dt1"].ToString(), out dateValue))
{
dt1.SelectedDate = dateValue;
}
(You provide very little details about error message etc...)

Remove selected item in combobox

I want to remove a selected item in my combobox
I have here a code upon form load, I am filling list items on combobox from database.
private void LoadComboField()
{
//string test = "<ROOT><DATA FieldGroup=\"PAYMENT_VIEW4\" FieldDescription=\"PNAME\" Output=\"1\" Filter=\"1\" FieldName=\"PATIENTNAME\" DataType=\"STRING\"/><DATA FieldGroup=\"PAYMENT_VIEW4\" FieldDescription=\"MEMID\" Output=\"1\" Filter=\"1\" FieldName=\"MEMBERID\" DataType=\"STRING\"/></ROOT>";
ReadXMLData(XMLDOC, dsCombo);
// ReadXMLData(test, dsCombo);
dt = dsCombo.Tables[0];
DataView dv1 = new DataView(dsCombo.Tables[0]);
this.cmbField.Items.Clear();
this.cmbField.DataSource = dv1;
this.cmbField.DisplayMember = "FieldDescription";
this.cmbField.ValueMember = "FieldName";
}
Then I have this code on SelectedValueChanged
private void cmbField_SelectedValueChanged(object sender, EventArgs e)
{
DataGridViewRow GridRowLoc = this.dgvFilter.CurrentRow;
AddGrid(iRowIdx);
int iRowCount = this.dgvFilter.RowCount - 1;
//this.dgvFilter.CurrentRow.IsNewRow
//if (GridRowLoc.IsNewRow) continue;
// MessageBox.Show(this.dgvFilter.RowCount.ToString());
if (this.cmbField.Text != "System.Data.DataRowView")
{
this.dgvFilter.Rows[iRowIdx].Cells["ColumnFieldName"].Value = this.cmbField.Text;
this.dgvFilter.Rows[iRowIdx].Cells["FieldName"].Value = this.cmbField.SelectedValue;
if (iRowCount <= iRowIdx)
{
DataRow drow = dttable.NewRow();
drow["ColumnNames"] = this.cmbField.Text;
drow["FieldName"]= this.cmbField.SelectedValue;
drow["Alias"]=string.Empty;
drow["DataType"]=string.Empty;
drow["Outputs"]=false;
drow["SortType"]=string.Empty;
drow["SortOrder"]=string.Empty;
drow["GroupBy"]=string.Empty;
drow["Filter"]=string.Empty;
drow["Or1"]=string.Empty;
drow["Or2"]=string.Empty;
drow["Or3"]=string.Empty;
drow["Or4"]=string.Empty;
drow["Or5"]=string.Empty;
drow["Or6"]=string.Empty;
drow["Or7"]=string.Empty;
drow["Or8"]=string.Empty;
drow["Or9"]=string.Empty;
drow["Or10"]=string.Empty;
dttable.Rows.Add(drow);
}
else
{
int irow = 0;
foreach (DataRow dr in dttable.Rows)
{
if (irow == iRowIdx)
{
dr["ColumnNames"] = this.cmbField.Text;
dr["FieldName"] = this.cmbField.SelectedValue;
}
irow++;
}
}
CheckAlias(iRowIdx, this.cmbField.Text, dgvFilter);
checkcellvalue(this.cmbField.Text, iRowIdx);
CheckSorting();
if (bGroupBySelected == true)
{
this.dgvFilter.Rows[iRowIdx].Cells["GroupBy"].Value = "Group By";
}
this.dgvFilter.DataSource = dttable;
dsFilter.AcceptChanges();
this.cmbField.Visible = false;
}
// checkcellvalue(this.cmbField.Text, iRowIdx);
//MessageBox.Show(arr_Filter[0]);
CheckoutputEnable();
}
I have this code in SelectedIndexChanged
try
{
DataTable dt1 = new DataTable();
DataRowView oDataRowView = cmbField.SelectedItem as DataRowView;
string sValue = string.Empty;
if (oDataRowView != null)
{
sValue = oDataRowView.Row["FieldDescription"] as string;
}
//int count = dttable.Rows.Count - 1;
ComboBox comboBox = (ComboBox)sender;
// Save the selected employee's name, because we will remove
// the employee's name from the list.
string selectedEmployee = (string)sValue;
int count = 0;
int resultIndex = -1;
// Call the FindStringExact method to find the first
// occurrence in the list.
resultIndex = cmbField.FindStringExact(selectedEmployee);
// Remove the name as it is found, and increment the found count.
// Then call the FindStringExact method again, passing in the
// index of the current found item so the search starts there
// instead of at the beginning of the list.
while (resultIndex != -1)
{
cmbField.Items.RemoveAt(resultIndex);
count += 1;
resultIndex = cmbField.FindStringExact(selectedEmployee,
resultIndex);
}
// Update the text in Textbox1.
txtName.Text = txtName.Text + "\r\n" + selectedEmployee + ": "
+ count;
}
//}
catch (Exception ex)
{
}
But it throws an exception, say that "items collection cannot be modified when the datasource property is set." I don't know how to fix this exception error, I think that's my only problem when removing an item on the combobox.
Please do help me on this one. Thanks in advance!
Use a BindingSource for your DataSource and CurrentItemChanged to react of changed items in CBO:
this.source = new BindingSource();
this.source.DataSource = loDs.Tables[0];
this.cmbField.DataSource = this.source;
this.source.CurrentItemChanged += source_CurrentItemChanged;
Example for eventHandler:
private void source_CurrentItemChanged(object sender, EventArgs e)
{
System.Data.DataRowView view = this.source.Current as System.Data.DataRowView;
if (view != null)
{
System.Diagnostics.Debug.WriteLine(view[0].ToString());
}
}
You can remove an item from the source like this:
this.source.RemoveAt(this.source.Find("FieldName", "PATIENTNAME"));
Show Details: A Detailed Data Binding Tutorial
You can't modify the Items collection when it comes from / is bound to a DataSource. Instead you need to modify the DataSource itself.
To delete the SelectedItem from the DataSource you can try this:
DataRowView item = cmbField.SelectedItem as DataRowView;
if (item != null) item.Delete();

Save checked row of one dataGrid into another dataGrid

I have a simple datagrid which Stores the data returned in json format in it. I have added unbound checkbox column to it. Now I want to Store only the checked rows in another datagrid. How should I proceed.
My Code
protected void BtnSave_Click(object sender, EventArgs e)
{
foreach (DataGridItem item in this.gv1.Items)
{
CheckBox chkBox =
(CheckBox)item.FindControl("ChkRows");
//If it's selected then add it to our new Datagrid
if (chkBox != null && chkBox.Checked)
{
//save
}
}
}
datasource for 1st grid
SearchAPIRequest.defaultApiKey = "samplekey";
SearchAPIRequest request = new SearchAPIRequest(rawName: txtUser.Text);
try
{
SearchAPIResponse response = request.Send();
DataTable dt = new DataTable();
dt.Columns.Add("Website");
dt.Columns.Add("first");
dt.Columns.Add("last");
dt.Columns.Add("jobs");
dt.Columns.Add("dobs");
dt.Columns.Add("educations");
dt.Columns.Add("addresses");
dt.Columns.Add("images");
dt.Columns.Add("URL");
for (int i = 0; i < response.Records.Count; i++)
{
DataRow dr = dt.NewRow();
dr["Website"] = response.Records[i].Source.Domain;
dr["First"] = response.Records[i].Names[0].First;
dr["Last"] = response.Records[i].Names[0].Last;
dr["jobs"] = response.Records[i].Jobs.Count > 0 ? response.Records[i].Jobs[0].Display: "";
dr["dobs"] = response.Records[i].DOBs.Count > 0 ? response.Records[i].DOBs[0].DateRange.Start.ToString() : "";
dr["images"] = response.Records[i].Images.Count> 0 ? response.Records[i].Images[0].Url:"";
dr["educations"] = response.Records[i].Educations.Count > 0 ? response.Records[i].Educations[0].Display : "";
dr["addresses"] = response.Records[i].Addresses.Count > 0 ? response.Records[i].Addresses[0].Display: "";
dr["URL"] = response.Records[i].Source.Url;
dt.Rows.Add(dr);
}
gv1.DataSource = dt;// response.Records[0].AllFields.ToList();
gv1.DataBind();

How to delete a row in dynamic Gridview?

I am working, as a test project, for a simple Inventory System in ASP.NET. In one page, I have to make the page for entering Purchase details! I used the dynamic gridview to ease the data entry. I have used this tutorial and this article but I am having problem in deleting the row in the gridview. I have seen this similar post but it was not helpful.
The aspx code is as below -
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Purchase Management</h2>
<asp:GridView ID="PurchaseMgmtGridView" runat="server" ShowFooter="True" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" GridLines="None" OnRowDeleting="PurchaseMgmtGridView_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="Item">
<ItemTemplate>
<asp:DropDownList ID="ItemDropDownList" runat="server" AppendDataBoundItems="true">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ItemUnit">
<ItemTemplate>
<asp:DropDownList ID="ItemUnitDropDownList" runat="server" AppendDataBoundItems="true">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Rate">
<ItemTemplate>
<asp:TextBox ID="RateTextBox" runat="server">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Qty.">
<ItemTemplate>
<asp:TextBox ID="QtyTextBox" runat="server">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total">
<ItemTemplate>
<asp:Label ID="TotalLabel" runat="server">
</asp:Label>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAddNewRow" runat="server" Text=" + " OnClick="ButtonAddNewRow_Click" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
</asp:Content>
And here is the aspx.cs Codes -
namespace SmoothInventoryWeb.Pages.ItemManagment
{
public class Item
{
public string Id { get; set; }
public string Name{get; set;}
}
public class ItemUnit
{
public string Id { get; set; }
public string Name{get; set;}
}
public partial class PurchaseManagementPage : System.Web.UI.Page
{
public List<Item> GetItemList()
{
List<Item> itemList = new List<Item>();
itemList.Add(new Item { Id = "1", Name = "Carpet" });
itemList.Add(new Item { Id = "2", Name = "Pasmina Muffler" });
itemList.Add(new Item { Id = "3", Name = "Large Carpet" });
return itemList;
}
public List<ItemUnit> GetItemUnitList()
{
List<ItemUnit> itemUnitList = new List<ItemUnit>();
itemUnitList.Add(new ItemUnit { Id = "1", Name = "Pieces" });
itemUnitList.Add(new ItemUnit { Id = "2", Name = "Dorzen" });
itemUnitList.Add(new ItemUnit { Id = "3", Name = "Gross" });
return itemUnitList;
}
List<Item> itemList = new List<Item>();
List<ItemUnit> itemUnitList = new List<ItemUnit>();
protected void Page_Load(object sender, EventArgs e)
{
this.itemList = GetItemList();
this.itemUnitList = GetItemUnitList();
if (!Page.IsPostBack)
addFirstRowInGridView();
}
private void FillItemDropDownList(DropDownList dropDownList)
{
if (dropDownList == null)
return;
foreach (Item item in itemList)
{
dropDownList.Items.Add(new ListItem(item.Name.ToString(), item.Id.ToString()));
}
}
private void FillItemUnitDropDownList(DropDownList dropDownList)
{
if (dropDownList == null)
return;
foreach (ItemUnit itemUnit in itemUnitList)
{
dropDownList.Items.Add(new ListItem(itemUnit.Name.ToString(), itemUnit.Id.ToString()));
}
}
protected void ButtonAddNewRow_Click(object sender, EventArgs e)
{
AddNewRow();
}
private void addFirstRowInGridView()
{
DataTable dataTable = new DataTable();
dataTable.Columns.Add(new DataColumn("Item", typeof(string)));
dataTable.Columns.Add(new DataColumn("ItemUnit", typeof(string)));
dataTable.Columns.Add(new DataColumn("Rate", typeof(string)));
dataTable.Columns.Add(new DataColumn("Qty", typeof(string)));
dataTable.Columns.Add(new DataColumn("Total", typeof(string)));
DataRow dataRow = dataTable.NewRow();
dataRow["Item"] = string.Empty;
dataRow["ItemUnit"] = string.Empty;
dataRow["Rate"] = string.Empty;
dataRow["Qty"] = string.Empty;
dataRow["Total"] = string.Empty;
dataTable.Rows.Add(dataRow);
ViewState["CurrentTable"] = dataTable;
PurchaseMgmtGridView.DataSource = dataTable;
PurchaseMgmtGridView.DataBind();
DropDownList itemDropDownList =
(DropDownList)PurchaseMgmtGridView.Rows[0].Cells[0].FindControl("ItemDropDownList");
DropDownList itemUnitDropDownList =
(DropDownList)PurchaseMgmtGridView.Rows[0].Cells[1].FindControl("ItemUnitDropDownList");
FillItemDropDownList(itemDropDownList);
FillItemUnitDropDownList(itemUnitDropDownList);
}
private void AddNewRow()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
DropDownList itemDropDownList =
(DropDownList)PurchaseMgmtGridView.Rows[rowIndex].Cells[0].FindControl("ItemDropDownList");
DropDownList itemUnitDropDownList =
(DropDownList)PurchaseMgmtGridView.Rows[rowIndex].Cells[1].FindControl("ItemUnitDropDownList");
TextBox rateTextBox =
(TextBox)PurchaseMgmtGridView.Rows[rowIndex].Cells[2].FindControl("RateTextBox");
TextBox qtyTextBox =
(TextBox)PurchaseMgmtGridView.Rows[rowIndex].Cells[3].FindControl("QtyTextBox");
Label totalLabel =
(Label)PurchaseMgmtGridView.Rows[rowIndex].Cells[4].FindControl("TotalLabel");
drCurrentRow = dtCurrentTable.NewRow();
dtCurrentTable.Rows[i - 1]["Item"] = itemDropDownList.SelectedItem.ToString();
dtCurrentTable.Rows[i - 1]["ItemUnit"] = itemUnitDropDownList.SelectedItem.ToString();
dtCurrentTable.Rows[i - 1]["Rate"] = rateTextBox.Text;
dtCurrentTable.Rows[i - 1]["Qty"] = qtyTextBox.Text;
dtCurrentTable.Rows[i - 1]["Total"] = totalLabel.Text;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
PurchaseMgmtGridView.DataSource = dtCurrentTable;
PurchaseMgmtGridView.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
SetPreviousData();
}
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++)
{
DropDownList itemDropDownList =
(DropDownList)PurchaseMgmtGridView.Rows[rowIndex].Cells[0].FindControl("ItemDropDownList");
DropDownList itemUnitDropDownList =
(DropDownList)PurchaseMgmtGridView.Rows[rowIndex].Cells[1].FindControl("ItemUnitDropDownList");
TextBox rateTextBox =
(TextBox)PurchaseMgmtGridView.Rows[rowIndex].Cells[2].FindControl("RateTextBox");
TextBox qtyTextBox =
(TextBox)PurchaseMgmtGridView.Rows[rowIndex].Cells[3].FindControl("QtyTextBox");
Label totalLabel =
(Label)PurchaseMgmtGridView.Rows[rowIndex].Cells[4].FindControl("TotalLabel");
FillItemDropDownList(itemDropDownList);
FillItemUnitDropDownList(itemUnitDropDownList);
if (i < dt.Rows.Count - 1)
{
//itemDropDownList.SelectedValue = dt.Rows[i]["Item"].ToString();
//itemUnitDropDownList.SelectedValue = dt.Rows[i]["ItemUnit"].ToString();
itemDropDownList.ClearSelection();
itemDropDownList.Items.FindByText(dt.Rows[i]["Item"].ToString()).Selected = true;
itemUnitDropDownList.ClearSelection();
itemUnitDropDownList.Items.FindByText(dt.Rows[i]["ItemUnit"].ToString()).Selected = true;
}
rateTextBox.Text = dt.Rows[i]["Rate"].ToString();
qtyTextBox.Text = dt.Rows[i]["Qty"].ToString();
totalLabel.Text = dt.Rows[i]["Total"].ToString();
rowIndex++;
}
}
}
}
protected void PurchaseMgmtGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
SetRowData();
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
int rowIndex = Convert.ToInt32(e.RowIndex);
if (dt.Rows.Count > 1)
{
dt.Rows.Remove(dt.Rows[rowIndex]);
drCurrentRow = dt.NewRow();
ViewState["CurrentTable"] = dt;
PurchaseMgmtGridView.DataSource = dt;
PurchaseMgmtGridView.DataBind();
for (int i = 0; i < PurchaseMgmtGridView.Rows.Count - 1; i++)
{
PurchaseMgmtGridView.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
}
SetPreviousData();
}
}
}
private void SetRowData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
DropDownList itemUnitDropDownList =
(DropDownList)PurchaseMgmtGridView.Rows[rowIndex].Cells[1].FindControl("ItemUnitDropDownList");
DropDownList itemDropDownList =
(DropDownList)PurchaseMgmtGridView.Rows[rowIndex].Cells[0].FindControl("ItemDropDownList");
TextBox rateTextBox =
(TextBox)PurchaseMgmtGridView.Rows[rowIndex].Cells[2].FindControl("RateTextBox");
TextBox qtyTextBox =
(TextBox)PurchaseMgmtGridView.Rows[rowIndex].Cells[3].FindControl("QtyTextBox");
Label totalLabel =
(Label)PurchaseMgmtGridView.Rows[rowIndex].Cells[4].FindControl("TotalLabel");
drCurrentRow = dtCurrentTable.NewRow();
//drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Item"] = itemDropDownList.SelectedItem.ToString();
dtCurrentTable.Rows[i - 1]["ItemUnit"] = itemUnitDropDownList.SelectedItem.ToString();
dtCurrentTable.Rows[i - 1]["Rate"] = rateTextBox.Text;
dtCurrentTable.Rows[i - 1]["Qty"] = qtyTextBox.Text;
dtCurrentTable.Rows[i - 1]["Total"] = totalLabel.Text;
rowIndex++;
}
ViewState["CurrentTable"] = dtCurrentTable;
}
}
else
{
Response.Write("ViewState is null");
}
}
}
}
These codes result something like this
But, as soon as I start to delete one of the rows, it gives me this exception -
This exception is thrown from the SetPreviousData() method from the following code -
DropDownList itemDropDownList = (DropDownList)PurchaseMgmtGridView.Rows[rowIndex].Cells[0].FindControl("ItemDropDownList");
Any idea where I got wrong?
P.S. : Code Updated I [supplied the codes for the list of entities i.e.Item and ItemUnit]
It doesn't look like it's actually the deleting of the row in the GridView that's the issue, but rather something else.
First, two things to note - I can't compile because I don't have the definitions for Item and ItemUnit, so I'm doing this by reading the code. Second, I haven't finished my coffee yet! (Update: My coffee is done!)
It looks like the reference to itemDropDownList in SetPreviousData() is null, so look into why that is. It might be easier to use a foreach loop to iterate through the rows of that DataTable to avoid any issues with 0-based indexes and count-1 comparisons, etc. (Update: It still would be easier, but it's not causing the issue.)
Also, not sure if you mean to do this, but the FindControl statement to get the ItemDropDownList is using rowIndex which is always equal to i. (Update: Again, could help just to clean up the code, but it's not a requirement.)
Start by figuring out what i is when it crashes and seeing if that's what you expect and figure out why the FindControl statement isn't working properly. If it's a 0, it may be trying to reading a header row or something where that Dropdown doesn't exist.
Sorry I can't give you a definitive solution, but hopefully this helps.
Solution:
After getting the full code, it was easier to see what happened. Basically, the PurchaseMgmtGridView_RowDeleting method was deleting the DropdownList from the GridView and then SetPreviousData() was trying to read something that didn't exist. The FindControl statement in SetPreviousData was returning NULL as indicated in the error message, but not for the reason I speculated earlier.
Remove the offending lines from the PurchaseMgmtGridView_RowDeleting method and you'll be all set.
protected void PurchaseMgmtGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
SetRowData();
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
int rowIndex = Convert.ToInt32(e.RowIndex);
if (dt.Rows.Count > 1)
{
dt.Rows.Remove(dt.Rows[rowIndex]);
drCurrentRow = dt.NewRow();
ViewState["CurrentTable"] = dt;
PurchaseMgmtGridView.DataSource = dt;
PurchaseMgmtGridView.DataBind();
// Delete this
//for (int i = 0; i < PurchaseMgmtGridView.Rows.Count - 1; i++)
//{
// PurchaseMgmtGridView.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
//}
SetPreviousData();
}
}
}
I think you trying to access on an object reference that points to null.
Try like this
private void SetPreviousData()
{
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count-1; i++)
{
DropDownList itemDropDownList =
(DropDownList)PurchaseMgmtGridView.Rows[i].Cells[0].FindControl("ItemDropDownList");
DropDownList itemUnitDropDownList =
(DropDownList)PurchaseMgmtGridView.Rows[i].Cells[1].FindControl("ItemUnitDropDownList");
TextBox rateTextBox =
(TextBox)PurchaseMgmtGridView.Rows[i].Cells[2].FindControl("RateTextBox");
TextBox qtyTextBox =
(TextBox)PurchaseMgmtGridView.Rows[i].Cells[3].FindControl("QtyTextBox");
Label totalLabel =
(Label)PurchaseMgmtGridView.Rows[i].Cells[4].FindControl("TotalLabel");
FillItemDropDownList(itemDropDownList);
FillItemUnitDropDownList(itemUnitDropDownList);
if (i < dt.Rows.Count - 1)
{
//itemDropDownList.SelectedValue = dt.Rows[i]["Item"].ToString();
//itemUnitDropDownList.SelectedValue = dt.Rows[i]["ItemUnit"].ToString();
itemDropDownList.ClearSelection();
itemDropDownList.Items.FindByText(dt.Rows[i]["Item"].ToString()).Selected = true;
itemUnitDropDownList.ClearSelection();
itemUnitDropDownList.Items.FindByText(dt.Rows[i]["ItemUnit"].ToString()).Selected = true;
}
rateTextBox.Text = dt.Rows[i]["Rate"].ToString();
qtyTextBox.Text = dt.Rows[i]["Qty"].ToString();
totalLabel.Text = dt.Rows[i]["Total"].ToString();
}
}
}
}
Refer here for Null Reference Exception

Categories

Resources