-1

I tried to generate one table using C# function. That table contains four columns. SerialNo (Value coming from API and it is label), Disposition result (dropdown-options coming from API) and two more text area.

While debuging, Getting Null exception error in Disposition result. in below line

string disposResult = ((HtmlSelect)row.Cells[1].FindControl("DropDownList1")).Value;

Below is the complete code

GRIDVIEW:

<asp:GridView ID="MyGridView" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="SerialNo" HeaderText="Serial No" />
        <asp:TemplateField HeaderText="Disposition result">                
            <ItemTemplate>                          
                <%# Eval("Disposition result") %>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Disposition comment">
            <ItemTemplate>
                <textarea runat="server" ID="txtDispositionComment" Rows="5" CssClass="form-control" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Note for Group">
            <ItemTemplate>
                <textarea runat="server" ID="txtNoteForGroup" Rows="5" CssClass="form-control" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Generating DataTable Source for gridview:

protected async void serialNoFieldData()
{
    string NMRValue = Request.QueryString["NMRValue"];
    string apiUrl = "https://itapps/nmrapi_V2/api/nmr?NMR_Number=" + NMRValue;
    using (HttpClient client = new HttpClient())
    {
        string apiResponse = await client.GetStringAsync(apiUrl);
        JObject responseData = JObject.Parse(apiResponse);
        JArray data = JArray.Parse(responseData["data"].ToString());

        DataTable dt = new DataTable();
        dt.Columns.Add("SerialNo");
        dt.Columns.Add("Disposition result");
        dt.Columns.Add("Disposition comment");
        dt.Columns.Add("Note for Group");

        // Get the dropdown values for the Disposition result column
        string dropdownApiUrl = "https://itapps/nmrapi_V2/api/DBParameter/NMR_Form?PN=DisposRes";
        string dropdownApiResponse = await client.GetStringAsync(dropdownApiUrl);
        JObject dropdownData = JObject.Parse(dropdownApiResponse);

        List<string> dropdownValues = new List<string>();
        if ((bool)dropdownData["success"])
        {
            JArray dataArray = (JArray)dropdownData["data"];
            foreach (string item in dataArray)
            {
                dropdownValues.Add(item);
            }
        }

        foreach (JObject item in data)
        {
            string serialNumber = (string)item["SerialNo"];

            // Populate the form fields with the retrieved values
            // Add a new row to the DataTable
            DataRow dr = dt.NewRow();
            dr["SerialNo"] = serialNumber;
            string dropdownHtml = CreateDropDownList(dropdownValues);
            dr["Disposition result"] = dropdownHtml;
            dr["Disposition comment"] = CreateTextArea();
            dr["Note for Group"] = CreateTextArea();
            dt.Rows.Add(dr);
        }

        // Bind the DataTable to a GridView control
        MyGridView.DataSource = dt;
        MyGridView.DataBind();
    }
}

Code for dropdown for Disposition result field:

private string CreateDropDownList(List<string> values)
{
    StringBuilder sb = new StringBuilder();
    sb.Append("<select id='DropDownList1' class='form-control' style='width: 200px;'>");

    foreach (string value in values)
    {
        sb.Append("<option value='" + value + "'>" + value + "</option>");
    }

    sb.Append("</select>");
    return sb.ToString();
}

My Expectation is : I want to get the value which i selected in dropdown. enter image description here

dpant
  • 1,622
  • 19
  • 30
Guru
  • 47
  • 6
  • 1
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Selvin Apr 04 '23 at 10:40
  • @Guru Generally, it is a good idea to strip code that other developers will be unable to execute off your samples (e.g. by replacing data originating from external resources with mock up data) and show exactly when and where your lines of code get executed (e.g. the button click event where you try to access the dropdownlist). – dpant Apr 07 '23 at 20:15
  • @dpant - yes i should have mentioned the btn_submit data also. let me update for you. – Guru Apr 10 '23 at 05:48

2 Answers2

0

I guess the line which throws the exception is called before you populate your grid? Set a breakepoint on the line and check which object is null. Maybe it's 'Cells[1]' because your grid has not 2 or more cells or maybe its 'FindControl("DropDownList1")' because you haven't called CreateDropDownList() yet.

Also your method 'CreateDropDownList' gets called multible times and every time it creates a html object with the same id. This is 100% cause you problems later when you want to get a specific select element.

HWS-SLS
  • 17
  • 4
  • thanks for your help! But, CreateDropDownList() is called during page load and `string disposResult = ((HtmlSelect)row.Cells[1].FindControl("DropDownList1")).Value;` is called during button click of the form. – Guru Apr 05 '23 at 04:01
0

You get that error because DropDownList1 does not really exist as a control in your web page. In WebForms, dynamic controls are not added to the page by code such as in your CreateDropDownList method.

Rather, you should define DropDownList in the grid column's ItemTemplate at design time and populate it with values by using the OnRowDataBound event of the grid, for example:

GridView:

<asp:GridView ID="MyGridView" runat="server" AutoGenerateColumns="False"       
    OnRowDataBound="MyGridView_RowDataBound">      
    <Columns>  
        <asp:BoundField DataField="SerialNo" HeaderText="Serial No" />
        <asp:TemplateField HeaderText="Disposition result">                
            <ItemTemplate>                          
                <asp:DropDownList ID="DropDownList1" runat="server">
                </asp:DropDownList>                
            </ItemTemplate>
        </asp:TemplateField>         
    </Columns>  
</asp:GridView>

<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

Code behind:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        LoadData();
    }
}

protected void LoadData()
{
    DataTable dt = new DataTable();
    dt.Columns.Add("SerialNo");

    DataRow dr = dt.NewRow();
    dr["SerialNo"] = "Serial 1";

    dt.Rows.Add(dr);

    MyGridView.DataSource = dt;
    MyGridView.DataBind();
}

protected void MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // Get the dropdown values for the Disposition result column
        // e.g. by calling your api:
        // https://itapps/nmrapi_V2/api/DBParameter/NMR_Form?PN=DisposRes

        List<ListItem> values = new List<ListItem>();
        values.Add(new ListItem("Disposition 1", "Disposition 1"));
        values.Add(new ListItem("Disposition 2", "Disposition 2"));
        values.Add(new ListItem("Disposition 3", "Disposition 3"));

        DropDownList DropDownList1 = (e.Row.FindControl("DropDownList1") as DropDownList);

        DropDownList1.DataTextField = "Text";
        DropDownList1.DataValueField = "Value";
        DropDownList1.DataSource = values;
        DropDownList1.DataBind();
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    // Get the selected value of the dropdownlist in first row
    DropDownList ddl1 = (MyGridView.Rows[0].FindControl("DropDownList1") as DropDownList);
    var disposResult = ddl1.SelectedValue;
}

In the above code, when Button1 is clicked, disposResult is assigned the selected value of the DropDownList in the first row of the grid.

Please, note that this is just an example using hardcoded, local data and is by no means optimized. For example, the GridView.RowDataBound event will be triggered for each row added to the grid. So, you may want to move the api call code to get the dropdown values outside the MyGridView_RowDataBound handler and only do the databinding at that point.

Hope that helps,

dpant
  • 1,622
  • 19
  • 30