DropDownList.DataSource NullReferenceException? - c#

I am getting null reference in by backend CS Code. Why is the DataTable null?
<asp:TemplateField HeaderText="Frequency" ItemStyle-Width = "150" >
<ItemTemplate>
<asp:Label ID="Frequency" runat="server" Text='<% # Eval("frequency") %>' ></asp:Label>
<asp:DropDownList ID="frequencydropdownlist" runat="server" Visible="false" ></asp:DropDownList>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="Addfrequencydropdownlist" runat="server"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
</Columns>
Code Behind:
public partial class CollectionHead : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable dtt = new DataTable();
string conString = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
SqlConnection con = new SqlConnection(conString);
SqlCommand mycommand = new SqlCommand();
mycommand.Connection = con;
mycommand.CommandText = "select ID,Frequency from FeesFrequency";
mycommand.CommandType = CommandType.Text;
mycommand.Connection = con;
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = mycommand;
sda.Fill(dtt);
DropDownList Addfrequencydropdownlist = CollectionHead_GridView.FindControl("Addfrequencydropdownlist") as DropDownList;
Addfrequencydropdownlist.DataSource = dtt.DefaultView;// null reference exception ????????
Addfrequencydropdownlist.DataTextField = "Frequency";
Addfrequencydropdownlist.DataValueField = "ID";
Addfrequencydropdownlist.DataBind();

Update You have to databind the grid first before you can access it's footer. Therefore i would use the RowDataBound event to fill the DropDownList:
protected void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList Addfrequencydropdownlist = (DropDownList)e.Row.FindControl("Addfrequencydropdownlist");
// ...
}
}
Old answer (might still be useful):
It is Addfrequencydropdownlist which is null after your try-cast because the NamingContainer of the DropDownList in the footer of the grid is not the grid itself but the FooterRow. So this is null causing the NullReferenceException:
CollectionHead_GridView.FindControl("Addfrequencydropdownlist")
You can use the FooterRow-property of the grid to get it's reference:
GridViewRow footer = CollectionHead_GridView.FooterRow;
DropDownList Addfrequencydropdownlist = (DropDownList)footer.FindControl("Addfrequencydropdownlist");
As an aside, i would use the as operator only if it isn't exceptional that it is null. Otherwise you're replacing a menaingful NullReferenceException with a bug in your code(in this case a NullReferenceException at the wrong place).
I would also wrap it in a if(!IsPostBack)-check to databind it only at the initial load and not on every postback if ViewState is enabled(default):
if(!IsPostBack)
{
DataTable dtt = new DataTable();
// rest of your code in Page_Load ....
}

Related

when try to add check box to grid view on asp.net forms i get error?

I work on asp.net web forms with c# I need to add checkbox column as last column on gridview
but i don't know how to add it
static string con =
"Data Source=DESKTOP-L558MLK\\AHMEDSALAHSQL;" +
"Initial Catalog=UnionCoop;" +
"User id=sa;" +
"Password=321;";
SqlConnection conn = new SqlConnection(con);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridViewSearch.DataSource = GetDataForSearch();
GridViewSearch.DataBind();
}
}
public DataTable GetDataForSearch()
{
string response = string.Empty;
SqlCommand cmd = new SqlCommand();
DataTable dt = new DataTable();
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "select top 10 datelogged AS EntredDatetime, Doc_type AS OrderType, Printer_name, BranchID AS BranchCode, id from Print_Report";
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 50000;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
}
catch (Exception ex)
{
response = ex.Message;
}
finally
{
cmd.Dispose();
conn.Close();
}
return dt;
}
on aspx page
<asp:GridView ID="GridViewSearch" runat="server">
</asp:GridView>
GridViewSearch.DataSource = GetDataForSearch();
DataGridViewCheckBoxColumn checkColumn = new DataGridViewCheckBoxColumn();
checkColumn.Name = "X";
checkColumn.HeaderText = "X";
checkColumn.Width = 50;
checkColumn.ReadOnly = false;
checkColumn.FillWeight = 10; //if the datagridview is resized (on form resize) the checkbox won't take up too much; value is relative to the other columns' fill values
GridViewSearch.Columns.Add(checkColumn);
GridViewSearch.DataBind();
I get error on line below
GridViewSearch.Columns.Add(checkColumn);
argument 1 can't convert from system.windows.forms.datagridviewcheckbox to system.web.ui.webcontrol.databoundfield
so how to solve this issue please ?
Seems to me, that if you want say a button, or check box, or dropdown?
why not just add it to the markup.
So, say like this:
<div id="MyGridPick" runat="server" style="display:normal;width:40%">
<asp:Label ID="lblSel" runat="server" Text="" Font-Size="X-Large"></asp:Label>
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" cssclass="table table-hover" OnRowDataBound="GridView1_RowDataBound" >
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" ItemStyle-Width="120px" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkSel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
Then my code to load is this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
SqlCommand cmdSQL =
new SqlCommand("SELECT * FROM tblHotelsA ORDER BY HotelName");
GridView1.DataSource = MyRstP(cmdSQL);
GridView1.DataBind();
}
Now, of course I get VERY tired of typing that connection string stuff over and over. So, I have a "genreal" routine like this:
public DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
cmdSQL.Connection = conn;
using (cmdSQL)
{
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
And the result of running above:
So, kind of hard to make the case to "add" a check box control, when you can just drop one into the gridview.
Same goes for a button, maybe we want a button to "view" or edit the above row, or some such.
So, once again, just drop in a plain jane button, say like this:
<asp:TemplateField HeaderText="View" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:Button ID="bView" runat="server" Text="View" CssClass="btn"
OnClick="bView_Click" />
</ItemTemplate>
</asp:TemplateField>
And now we have this:
And EVEN better?
Well, since that button (or check box) is a plain jane standard control?
then you can add standard events, like a click event, or whatever you want.
Say this code for the button click (shows how to get current row).
protected void bView_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
GridViewRow gRow = btn.NamingContainer as GridViewRow;
int PKID = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
SqlCommand cmdSQL =
new SqlCommand("SELECT * FROM tblHotelsA WHERE ID = #ID");
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PKID;
DataTable dtHotel = MyRstP(cmdSQL);
General.FLoader(MyEditArea, dtHotel.Rows[0]);
MyGridPick.Style.Add("display", "none"); // hide grid
MyEditArea.Style.Add("display", "normal"); // show edit div area
}
And we now get/see this:
Edit: Process each checked/selected row.
this:
protected void cmdSelProcess_Click(object sender, EventArgs e)
{
// process all rows in GV with check box
String sPK = "";
List<int> MySelected = new List<int>();
foreach (GridViewRow gRow in GridView1.Rows)
{
CheckBox chkSel = (CheckBox)gRow.FindControl("chkSel");
if (chkSel.Checked)
{
int PK = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
// add pk value of row to our list
MySelected.Add(PK);
// Or we could process data based on current gRow
if (sPK != "")
sPK += ",";
sPK += PK.ToString();
Debug.Print(PK.ToString());
}
}
// at this point, we have a nice list of selected in MySelected
// or, maybe process as a data table
SqlCommand cmdSQL =
new SqlCommand($"SELECT * FROM tblHotelsA where ID IN({sPK})");
DataTable rstSelected = MyRstP(cmdSQL);
//
foreach (DataRow dr in rstSelected.Rows)
{
// do whatever
}
}
Datagridviewcheckboxcolumn is a Windows formx object. You are working in web forms. Please see the link below for information on the webforms check box field
CheckBoxField checkColumn = new CheckBoxField();

Update grid view/db with combo box selected value :ASP.NET C#

i need to create a webpage containing a grid view with combo box. condition is:- the combo box value should be inserted on my SQL db and update the db/grid view when i click save button.[i added the image of proposed design of the page]any help with the code is so much appreciated! thank you!
GridView Markup
Below I have a simple GridView ASP.Net GridView control populated from the Customers table of Northwind database. It displays 2 columns Contact Name and City of which city is editable via ASP.Net DropDownList control. The identifier column Customer Id is bind to the DataKeyNames property.
<asp:GridView ID="gvCustomers" DataKeyNames = "CustomerId" runat="server" AutoGenerateColumns = "false" OnRowEditing = "EditCustomer" OnRowDataBound = "RowDataBound" OnRowUpdating = "UpdateCustomer" OnRowCancelingEdit = "CancelEdit">
<Columns>
<asp:BoundField DataField = "ContactName" HeaderText = "Contact Name" />
<asp:TemplateField HeaderText = "City">
<ItemTemplate>
<asp:Label ID="lblCity" runat="server" Text='<%# Eval("City")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblCity" runat="server" Text='<%# Eval("City")%>' Visible = "false"></asp:Label>
<asp:DropDownList ID = "ddlCities" runat = "server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
Binding the GridView
Below is the code to Bind the GridView control with data.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
}
}
private void BindData()
{
string query = "SELECT top 10 * FROM Customers";
SqlCommand cmd = new SqlCommand(query);
gvCustomers.DataSource = GetData(cmd);
gvCustomers.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
Editing the GridView Row
The below events handle the GridView Row Edit and Cancel Edit Events
C#
protected void EditCustomer(object sender, GridViewEditEventArgs e)
{
gvCustomers.EditIndex = e.NewEditIndex;
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
gvCustomers.EditIndex = -1;
BindData();
}

GridViewRowCommand cant find header row textbox value

i am trying to insert into sql table using gridview header template, under the gridview rowcommand i am trying to find the control and it is not able to retrieve the value.
protected void GridView1_RowCommand1(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Insert")
{
string NetWeightConnectionStrings = ConfigurationManager.ConnectionStrings["NetWeightConnectionString"].ToString();
string query = "INSERT INTO [Net Weight Tracking] ([Date])VALUES (#Date)";
using (SqlConnection sqlConn = new SqlConnection(NetWeightConnectionStrings))
using (SqlCommand cmd = new SqlCommand(query, sqlConn))
{
String Date = ((TextBox)GridV1.HeaderRow.FindControl("TextBox31")).Text;
cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = DateTime.ParseExact(((TextBox)GridV1.HeaderRow.FindControl("TextBox31")).Text, "dd/MM/yyyy", null);
sqlConn.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
GridV1.DataSource = dt;
GridV1.DataBind();
sqlConn.Close();
}
}
}
any help is much appreciated
You can try the RowDataBound Event to get the header template controls.
protected void GridView1__RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
TextBox txtControl = (TextBox)e.Row.FindControl("TextBox31");
}
}
EDIT 1
From the link shared for the GridView Mark up, TextBox31 is not in the HeaderItemTemplate, it is in EditItemTemplate. That would be the reason, you are not able to find the textbox.
<EditItemTemplate>
<asp:TextBox ID="TextBox31" runat="server" Text='<%# Bind("Field4") %>'></asp:TextBox>
</EditItemTemplate>

Gridview not detecting checkboxes being checked

What i'm trying to do is execute some code when a checkbox in a gridview is checked, with the code being executed row by row. I debugged the code and every time returns false despite the checkboxes being checked. The code i'm trying to execute works if the conditional statement is removed.
protected void ShoppingCartButton_Click(object sender, EventArgs e)
{
Label1.Text = "HIH0HI";
OleDbConnection myconn = new OleDbConnection();
myconn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|ProjectDatabase.accdb";
string UserID = Session["UserID"].ToString();
StringBuilder sb3 = new StringBuilder();
foreach (GridViewRow row in GridView1.Rows)
{
string unpredictable = "";
bool hi = true;
unpredictable = row.Cells[1].Text;
CheckBox chk = row.Cells[0].Controls[1] as CheckBox;
hi = chk.Checked;
sb3.Append(hi.ToString());
if (hi==true)
{
string command1 = "insert into Cart ([Username],[GameID]) values (#Username, #GameID)";
OleDbCommand cmd = new OleDbCommand(command1, myconn);
cmd.Parameters.AddWithValue("#Username", UserID);
cmd.Parameters.AddWithValue("#GameID", unpredictable);
myconn.Open();
cmd.ExecuteNonQuery();
myconn.Close();
}
}
Label1.Text = sb3.ToString();
}
Markup for the button and the gridview
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="True" EmptyDataText ="Data Entry Error">
<Columns>
<asp:TemplateField HeaderText ="Add to Cart?">
<ItemTemplate>
<asp:CheckBox ID="checkbx" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button runat="server" id="ShoppingCartButton" Text="Add to shopping cart" OnClick="ShoppingCartButton_Click" />
This was a simple one. Have to enclose any data binding logic in
if (!IsPostBack)

values not show in dropdownlist

i try to add values in dropdownlist in gridview query works fine but it appears as this ..
gridview html
<asp:BoundField HeaderText="ApproveID" DataField="ApproveID" ></asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%#
Eval("ApproveID") %>' Visible = "false" />
<asp:DropDownList ID="DropDownList4" runat="server"
class="vpb_dropdown">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
code
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddlCountries = (e.Row.FindControl("DropDownList4") as
DropDownList);
ddlCountries.DataSource = GetData("SELECT ApproveID,ApproveType FROM
ApproveType");
ddlCountries.DataTextField = "ApproveType";
ddlCountries.DataValueField = "ApproveID";
ddlCountries.DataBind();
//Add Default Item in the DropDownList
ddlCountries.Items.Insert(0, new ListItem("Please select"));
//Select the Country of Customer in DropDownList
//string country = (e.Row.FindControl("lblCountry") as Label).Text;
//ddlCountries.Items.FindByValue(country).Selected = true;
}
}
values are not inside in dropdownlist ..how to show values in dropdown??
and when i debug the code it cant show me any error
getdata code
private DataSet GetData(string query)
{
string conString =
ConfigurationManager.ConnectionStrings["mydms"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
Set
DropDownList1.SelectedValue = "Some Value";
then you will get the value as default
Get data function returns null or empty value so it wont through error or exception while debugging.Your code working fine better check data in the database.
In a project I participated we returned the DataTable instead of DataSet and it was working fine with dropdowns. We had code like this:
if( ds.Tables.Count == 1)
return ds.Tables[0];
else
return new DataTable();
Besides I would change the way of databinding. In my opinion using ObjectDataSource is a better approach becuase the event is called only when the data is needed and you don't have to do checks like this:
if (e.Row.RowType == DataControlRowType.DataRow)
After your last comment you should check if the DataSet contains the record you want ot set as selected:
if (ddlCountries.Items.FindByValue(country) != null)
{
ddlCountries.Items.FindByValue(country).Selected = true;
}

Categories