-1

I am new to asp. I get the below error, while transferring selected rows into data table. I want all the rows as labels.

string EmployeeID = (row.Cells[3].FindControl("M_ID")).ToString();

and stack trace,

[NullReferenceException: Object reference not set to an instance of an object.] _Default.vilemail_Click(Object sender, EventArgs e) in d:\Vinoth\Msmtest\vessel_inti.aspx.cs:79
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +111
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565

I know this is not much difficult, but I can't solve.

Mahe
  • 1,170
  • 1
  • 10
  • 22

3 Answers3

0

This will prevent exeception:

string EmployeeID = row.Cells[3].FindControl("M_ID") != null ? (row.Cells[3].FindControl("M_ID")).ToString() : string.Empty;

But you have to check in which condition row.Cells[3].FindControl("M_ID") getting null value.

Ankush Madankar
  • 3,364
  • 4
  • 34
  • 69
0

Judging by your question, this may what you need. Assuming that M_ID is a label id,

string EmployeeID = (row.Cells[3].FindControl("M_ID") as Label).Text;

You must specify what type of control you want to fetch from the page. In your case, it is a label, followed by the attribute of the control.

Mahe
  • 1,170
  • 1
  • 10
  • 22
0

Looks like you are trying to get the Id of an Employee. In this case I prefer make this Id key of the row:

<asp:GridView ID="EmployeesGridView" runat="server" DataKeyNames="EmployeeID">
    <Columns>
        <asp:BoundField DataField="EmployeeID" HeaderText="Employee" />
    </Columns>
</asp:GridView>

In this case when SelectedIndexChanged event fire you can get that key like this:

string EmployeeID = EmployeesGridView.SelectedDataKey.Value.ToString();

Edit In case you already have a DataKeyName or you need more than one value from there just add all properties you need in the DataKeyNames in the grid like this:

<asp:GridView ID="EmployeesGridView" runat="server" DataKeyNames="EmployeeID,ID">
    <Columns>
        <asp:BoundField DataField="EmployeeID" HeaderText="Employee" />
        <asp:BoundField DataField="ID" HeaderText="Id" />
    </Columns>
</asp:GridView>

And you can get them like this:

string EmployeeID = EmployeesGridView.SelectedDataKey.Value.ToString();
string id = EmployeesGridView..SelectedDataKey.Values["ID"].ToString();

Just remember that you need to think those values are primary keys of your grid so you can't have more than one row with same values/pairs.

Vitor Canova
  • 3,778
  • 4
  • 27
  • 55