Object is set to Null Reference when editing gridview - c#

In my web application, I have a grid-view and this grid-view is databounded. Above this grid-view, I have a text box where user can first enter the Employee ID and show the Employee Name in the grid view. In the grid view, it has the edit icon. When the user hit that edit icon, some text boxes in the grid view will appear and the use can edit the text in the text box. I got it working so far. However, my problem is when I am trying to edit the empty text box in the grid view, it gave me this error:
Object is not set to an instance of an object
All I did is to check if the text box is null. This does ignore the error but not really what I want
protected void txtEditedEmployeeID_TextChanged(object sender, EventArgs e)
{
DatabaseManager dbManager = Common.GetDbManager();
foreach (GridViewRow row in gridViewAddEmployee.Rows)
{
TextBox txtEmployee= (TextBox)row.FindControl("txtEmployeeID");
if (txtEmployee!= null)
{
string personID = txtEmployee.Text;
DataSet dsRE = dbManager.GetEmployeeNameByID(personID);
for (int i = 0; i < dsRE.Tables[0].Rows.Count; i++)
{
string employeeFirstName = dsRE.Tables[0].Rows[i]["FIRST_NAME"].ToString();
string employeeLastName = dsRE.Tables[0].Rows[i]["LAST_NAME"].ToString();
((TextBox)row.FindControl("txtEmployeeName")).Text = staffLastName + " " + staffFirstName;
}
}
else
{
}
}
}
HTML ASP.NET Code
<asp:TemplateField HeaderText="EmployeeID">
<EditItemTemplate>
<asp:TextBox ID="txtEmployeeID" runat="server" AutoPostBack="true" OnTextChanged= "txtEditedEmployeeID_TextChanged" Text='<%#Bind("Employee_ID") %>'Width="90px"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblEmployeeID" runat="server" CssClass="GridInput" Text='<%#Bind("Employee_ID") %>'Width="90px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Employee Name">
<EditItemTemplate>
<asp:TextBox ID="txtEmployee" runat="server" ReadOnly ="true" Text='<%#Bind("Full_Name") %>'Width="90px"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblEmployeeName" runat="server" CssClass="GridInput" Text='<%#Bind("Full_Name") %>'Width="90px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>

As on Edit txtEmployeeID will appear for that row only Not for all the rows of GridView and on TextBox Change event you are finding all row edited TextBox which is not appear till now so you may try this:
protected void txtEditedEmployeeID_TextChanged(object sender, EventArgs e)
{
DatabaseManager dbManager = Common.GetDbManager();
TextBox txt = sender as TextBox; // Edited TextBox
GridViewRow row = (txt.NamingContainer as GridViewRow);// Row of Edited TextBox
TextBox txtEmployee= (TextBox)row.FindControl("txtEmployeeID");
string personID = txtEmployee.Text;
DataSet dsRE = dbManager.GetEmployeeNameByID(personID);
for (int i = 0; i < dsRE.Tables[0].Rows.Count; i++)
{
string employeeFirstName = dsRE.Tables[0].Rows[i]["FIRST_NAME"].ToString();
string employeeLastName = dsRE.Tables[0].Rows[i]["LAST_NAME"].ToString();
((TextBox)row.FindControl("txtEmployeeName")).Text = staffLastName + " " + staffFirstName;
}
}

Try this:
Instead of
TextBox txtEmployee= (TextBox)row.FindControl("txtEmployeeID");
if (txtEmployee!= null)
{
string personID = txtEmployee.Text;
You should write it like this
TextBox txtEmployee = new TextBox();
txtEmployee = (TextBox)row.FindControl("txtEmployeeID");
if (!string.isNullorEmpty(txtEmployee.Text))
{
string personID = txtEmployee.Text;

Related

how to find a label in the itemtemplate on gridview?C# ASP.NET

I have a GridView that bound some data from DB and have a label in the ItemTemplate and EditTextbox in the EditItemTemplate they are in the same TemplateField. In the GridView some user has no data in somewhere field, If I want to insert a data for these user, I need to find GirdView label first and var the edittextbox, when updating I can Compare the value of them , such as the edittextbox value not equals to labeldata value then insert,
but I can't find the value of the label when rowupdating or databound of gridview
how can i do it ?
I have try
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
int rowCount = GridView1.Rows.Count;
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (rowCount >= 1)
{
Label lbDA_TEL_HK_NO = ((Label)e.Row.FindControl("lblKM_TEL"));
Session["DA_TEL_HK_NO"] = lbDA_TEL_HK_NO.Text;
}
}
}
It can find all the gridview data but not which I selected
P.S I'm a newbie, please help me
<asp:TemplateField ItemStyle-Width = "150px" HeaderText = "香港內線">
<ItemTemplate>
<asp:Label ID="lblHK_TEL" runat="server"
Text='<%# Eval("[DA_TEL_HK_NO]")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtHK_TEL" runat="server" onkeyup="this.value=this.value.replace(/[^0-9]/g,'')" MaxLength="3"
Text='<%# Eval("[DA_TEL_HK_NO]")%>'></asp:TextBox>
</EditItemTemplate>
You can try something like this for read all rows in grid view:
for (var i = 0; i < GridView1.Rows.Count; i++)
{
var label = GridView1.Rows[i].FindControl("lblKM_TEL") as Label;
if (label != null)
{
// Manipulate label control
}
}
Or you can gets label from selected row:
var label = GridView1.SelectedRow.FindControl("lblKM_TEL") as Label;
if (label != null)
{
// Manipulate label control
}
From your aspx markup you are using the wrong label id .
you need yo use this label id lblHK_TEL
You code looks as follows after changes
Label lbDA_TEL_HK_NO = ((Label)e.Row.FindControl("lblHK_TEL"));

Pass Gridview one Row TextBox value To Another Row Textbox Value

I have Gridview with 10 Rows each row have 2 columns which is Textbox and Checkbox.
what i have to do is have to enter textbox Value as 1000 and i Clicked the Checkbox at first Row then value must go to Textbox of Second row and i clicked checkbox of Second Row then value must be go to third row of Textbox and so on.
i tried this,
protected void txtintroId_TextChanged(object sender, EventArgs e)
{
TextBox txt = (TextBox)sender;
GridViewRow grid = ((GridViewRow)txt.Parent.Parent.Parent);
TextBox txtIntro = (TextBox)txt.FindControl("txtintroId");
}
here i get the 1st row Value but How do i pass this to second Row.
Assist me
Here is full working code(as per your requirement )
Create a gridview like this
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%#Eval("txtcolumn") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="True" OnCheckedChanged="CheckBox2_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Add a function in code behind C#
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
int rowNo=0;
foreach (GridViewRow GV1 in GridView1.Rows)
{
rowNo++;//
if (rowNo < GridView1.Rows.Count) //Checking that is this last row or not
{
//if no
CheckBox chkbx= (CheckBox)GV1.FindControl("CheckBox1");
TextBox curenttxtbx = (TextBox)GV1.FindControl("TextBox1");
if (chkbx.Checked == true )
`{
int nextIndex = GV1.RowIndex + 1;//Next row
TextBox txtbx = (TextBox)GridView1.Rows[nextIndex].FindControl("TextBox1");
txtbx.Text = curenttxtbx.Text;
}
}
//if yes
else
{
//For last row
//There is no next row
}
}
}
And i used this data table as data source
DataTable table = new DataTable();
table.Columns.Add("txtcolumn", typeof(string));
table.Rows.Add("1");
table.Rows.Add("32");
table.Rows.Add("32");
table.Rows.Add("32");
table.Rows.Add("3");
table.Rows.Add("32");
table.Rows.Add("32");
I tested this code it is working as per your requirement. (And SORRY for this bad formatting. i will do it later or please some body correct the formating :))

Add text from c# code to a gridview label

I need to add an specific text in an itemtemplate on a gridview...
right now I have this in my gridview
<asp:TemplateField HeaderText="Total" SortExpression="Total" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Label ID="lblTotal" runat="server" Text='<%#Math.Round(Convert.ToDouble(Eval("Total")), 2).ToString("C") + " M.N."%>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
in the part where it says
<asp:Label ID="lblTotal" runat="server" Text='<%#Math.Round(Convert.ToDouble(Eval("Total")), 2).ToString("C") + " M.N."%>'>
I made an specific text, but it will always be the same text (well except in the Eval of course)... But I need to get the format I need from this method.
public static string GetFormatoMoneda(decimal decCantidad)
{
//Get data from currency (Dollars, Pesos, Euros, etc.)
DataRow dr = ConexionBD.GetInstanciaConexionBD().GetTipoDeMonedaPrincipal((int)HttpContext.Current.Session["Grupo"]);
return dr["Signo"] + Math.Round(decCantidad, 2).ToString("C").Substring(1) + " " + dr["Abreviatura"];
}
I use this method to get a specific string and use it on labels (I assign it on code on the cs file)..
But in this case... I have to insert that text on the column of a gridview...
How can I get that string value and insert it on a label inside of a templatefield/itemtemplate??
Instead of ...
Text='<%#Math.Round(Convert.ToDouble(Eval("Total")), 2).ToString("C") + " M.N."%>'
...use
Text='<%#GetFormatoMoneda(Eval("Total"))%>'
However, this assumes that GetFormatoMoneda is in the same class as the web form. If not, then you need to include the class name, e.g.
Text='<%#MyClass.GetFormatoMoneda(Eval("Total"))%>'
Then you either need to make a change to GetFormatoMoneda to use an object type parameter, e.g.
public static string GetFormatoMoneda(object objCantidad)
{
var decCantidad = Convert.ToDecimal(decCantidad);
//Get data from currency (Dollars, Pesos, Euros, etc.)
DataRow dr = ConexionBD.GetInstanciaConexionBD().GetTipoDeMonedaPrincipal((int)HttpContext.Current.Session["Grupo"]);
return dr["Signo"] + Math.Round(decCantidad, 2).ToString("C").Substring(1) + " " + dr["Abreviatura"];
}
or use another method with an object parameter and call GetFormatoMoneda(decimal), passing in the correct value, such as
protected string CorrectFormat(object obj)
{
return GetFormatoMoneda(Convert.ToDecimal(obj));
}
in which case you would use
Text='<%#CorrectFormat(Eval("Total"))%>'
If you wanted to do it programmatically, this would work:
Default.aspx:
<asp:GridView ID="gvGrid" runat="server" AutoGenerateColumns="false" OnRowDataBound="gvGrid_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblTotal" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Generate fake data
var data = Enumerable.Range(1, 20);
//Give the data to the grid
gvGrid.DataSource = data;
gvGrid.DataBind();
}
}
protected void gvGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the control
var lblTotal = (Label)e.Row.FindControl("lblTotal");
//Get the data for this row
var data = (int)e.Row.DataItem;
//Display the data
lblTotal.Text = data.ToString();
}
}

asp.NET Drop Down List within a Grid View - Getting the selected value

I have a status drop down list which I am using within a grid view, the users can select a list item they want when editing a row within the grid view. The problem is that the current implementation is not retrieving the selected value, but is only retrieving the default/loaded value.
This is the defination of the grid view:
<asp:GridView ID="applicationGrid" runat="server" Width="95%"
AutoGenerateEditButton="True"
AutoGenerateColumns="False"
ShowFooter="True"
CellSpacing="10"
HeaderStyle-HorizontalAlign="Left"
ItemStyle-HorizontalAlign="Left"
OnRowUpdating="applicationGrid_RowUpdating"
OnRowEditing="applicationGrid_RowEditing"
OnRowCancelingEdit="applicationGrid_RowCancelingEdit"
AutoPostBack="true" >
And this is the defination of the Column where the dropdown list will appear on edit:
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Label ID="StatusDescription" runat="server" Text='<%# Eval("STATUS_DESCRIPTION") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="StatusDescriptionList" runat="server" DataTextField="status_description"
DataValueField="application_status_code" OnLoad="DropDownLoadEdit">
<asp:ListItem Text="Status:" Value="default"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
This is the code behind which is handling the update scenario:
protected void applicationGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = applicationGrid.Rows[e.RowIndex];
applicationGrid.EditIndex = -1;
Label applicationCodeLabel = row.FindControl("AppID") as Label;
TextBox applicationNameTextBox = row.FindControl("AppNameEdit") as TextBox;
TextBox applicationURLTextBox = row.FindControl("AppURLEdit") as TextBox;
DropDownList applicationStatusDropDownList = row.FindControl("StatusDescriptionList") as DropDownList;
int applicationCode = Convert.ToInt32(applicationCodeLabel.Text);
string applicationName = applicationNameTextBox.Text;
string applicationURL = applicationURLTextBox.Text;
int applicationStatus = Convert.ToInt32(applicationStatusDropDownList.SelectedValue.ToString());
//string applicationStatus2 = applicationStatusDropDownList.SelectedItem.Value;
//string applicationStatus3 = applicationStatusDropDownList.SelectedItem.Text;
application.UpdateApplication(applicationCode, applicationName, applicationURL);
PopulateApplications();
}
All is working, but the selected value is not the one which the is loaded and not the one which the user selects. Therefore the problem is getting the selected value from the list. What needs to be changed, and why?
protected void applicationGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = applicationGrid.Rows[e.RowIndex];
applicationGrid.EditIndex = -1;
Label applicationCodeLabel = row.FindControl("AppID") as Label;
TextBox applicationNameTextBox = row.FindControl("AppNameEdit") as TextBox;
TextBox applicationURLTextBox = row.FindControl("AppURLEdit") as TextBox;
DropDownList applicationStatusDropDownList = row.FindControl("StatusDescriptionList") as DropDownList;
int applicationCode = Convert.ToInt32(applicationCodeLabel.Text);
string applicationName = applicationNameTextBox.Text;
string applicationURL = applicationURLTextBox.Text;
int applicationStatus = Convert.ToInt32(applicationStatusDropDownList.SelectedValue.ToString());
//string applicationStatus2 = applicationStatusDropDownList.SelectedItem.Value;
//string applicationStatus3 = applicationStatusDropDownList.SelectedItem.Text;
application.UpdateApplication(applicationCode, applicationName, applicationURL);
PopulateApplications();
}
EDIT: Adding my Populate Methods:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
PopulateApplications();
}
catch (Exception exception)
{
throw exception;
}
}
}
private void PopulateApplications()
{
DataTable reader = application.GetApplicationList();
applicationGrid.DataSource = reader;
applicationGrid.DataBind();
applicationGrid.AllowSorting = true;
}
protected void DropDownLoadEdit(object sender, EventArgs e)
{
DataTable statusTable = application.GetStatusList();
DropDownList dropdown = sender as DropDownList;
dropdown.DataSource = statusTable;
dropdown.DataTextField = "status_description";
dropdown.DataValueField = "application_status_code";
dropdown.DataBind()
}
Update #2: I am trying to fill up a static variable in the class which is for the selected index. This will then be used when update is pressed. However, this is still getting the original value of the drop down list and not the selected one.
This is the method:
protected void StatusDescriptionList_SelectedIndexChanged(object sender, System.EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
selectedValue = Convert.ToInt32(ddl.SelectedValue.ToString());
}
Are you repopulating the list in DropDownLoadEdit, regardless of whether the transition is a postback or not? If so, the list will be repopulated before its value is read, and set to the default before your method has a chance to read the value.
The issue may be of the post back.
Once the item is selected from the drop down the page get post back the value you selected get vanished.
To over come this issue. Bind the drop down list inside page is post back or else make use of a Ajax update panel.
#Ryan, Have you done this
'
AutopostBack="True"
<asp:DropDownList ID="StatusDescriptionList" runat="server" AutopostBack="True" DataTextField="status_description"
DataValueField="application_status_code" OnLoad="DropDownLoadEdit">
<asp:ListItem Text="Status:" Value="default"></asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="StatusDescriptionList" runat="server" DataTextField="status_description"
DataValueField="application_status_code" SelectedValue="application_status_code" AutopostBack="True" OnLoad="DropDownLoadEdit">
<asp:ListItem Text="Status:" Value="default"></asp:ListItem>
</asp:DropDownList>

adding functionality to an imageButton in a gridview

Hallo there
I have an ImageButton control as part of a GridView control that is displayed as an ItemTemplate and in the same GridView I have a regular Button control to which I added some code like this.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "addToSession")
{
//get the row index stored in the CommandArgument property
int index = Convert.ToInt32(e.CommandArgument);
//get the gridview row where the command is raised
GridViewRow selectedRow = ((GridView)e.CommandSource).Rows[index];
//values stored in the text property of the cells
string ISBN = selectedRow.Cells[0].Text;
string bookTitle = selectedRow.Cells[1].Text;
string image = selectedRow.Cells[2].Text;
Service s = new Service();
Session["ISBN"] = ISBN;
Session["bookTitle"] = bookTitle;
Session["ImageUrl"] = s.returnImageUrl(bookTitle);
if (Session["userName"] == null)
{
Response.Redirect("registerPage.aspx");
}
else
{
Response.Redirect("RateBook.aspx");
}
}
else if (e.CommandName == "ratedBooks")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = ((GridView)e.CommandSource).Rows[index];
string bookTitle = selectedRow.Cells[1].Text;
Service s = new Service();
Session["ImageUrl"] = s.returnImageUrl(bookTitle);
Response.Redirect("BookRated.aspx");
}
when I run this code I get a format exception and again I am not sure why.
I have altered the image button a bit and nested the image in a link button which seems to be more correct.
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="ratedBooks">
<asp:Image ID="ImageButton1" ImageUrl='<%#Eval("pictureUrl") %>'
runat="server" />
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Advice perhaps as to what to do
regards
ImageButton.CommandName is a valid property and it should work the same as Button.CommandName.
The problem, then, is most likely in your GridView1_RowCommand procedure. Can you post the entire procedure code including the part intended to handle the ImageButton click?

Categories

Resources