Microsoft
Software
Hardware
Network
Question : Gridview Update Error, Cannot insert Null Value into DB. Controls all returning null values
Scenario: I have a Gridview with several dropdownlist controls in the ItemEditTemplates to control user editing capabilities. The Dropdowns Display a region Name which is text but the update needs to update an int value which is the RegionID.
Problem. When I click edit and then update I get the following error:
Cannot insert the value NULL into column 'RegionID', table 'xxx.dbo.SiteDBTable'; column does not allow nulls. UPDATE fails.
The statement has been terminated.
What seems be happening in the Gridview controls is that they are all returning null values. I was trying confirm this by adding the following code in the RowEditing Event to to troubleshoot and view each of the values of the controls:
protected void gvMain_RowEditing(object sender, GridViewEditEventArgs e)
{
gvMain.EditIndex = e.NewEditIndex;
TextBox txtYearEdit = (TextBox)gvMain.Rows[gvMai
n.EditInde
x].FindCon
trol("txtY
earEdit");
DropDownList ddlRegion= (DropDownList)gvMain.Rows[
gvMain.Edi
tIndex].Fi
ndControl(
"ddlRegion
");
DropDownList ddlSetSite = (DropDownList)gvMain.Rows[
gvMain.Edi
tIndex].Fi
ndControl(
"ddlSetSit
e");
string testYear = txtYearEdit.Text;
string testSetSite = ddlSetSite.SelectedValue;
string testRegion = ddlRegion.SelectedValue;
}
When this code hits the test strings I can see while debugging that the instances of the Dropdownlist and TextBox objects are null.
Here is a Code snippet of one the Controls
<asp:TemplateField HeaderText="Region" SortExpression="Region">
<EditItemTemplate>
<asp:DropDownList ID="ddlRegionZone" runat="server" AppendDataBoundItems="True
"
DataSourceID="dsrcRegionDD
L" DataTextField="Region" DataValueField="RegionID" SelectedValue='<%# Bind("RegionID") %>'>
<asp:ListItem Selected="True" Value="0">-</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Region") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Looking for any help on how to fix this or a better way to troubleshoot this problem.
Answer : Gridview Update Error, Cannot insert Null Value into DB. Controls all returning null values
Try doing the above test in the RowUpdating event but remove the first line where you are setting the editIndex.
And also I see your DDL name in markup is ddlRegionZone and you are trying to fing ddlRegion..
Random Solutions
adding a mac to sbs 2003 network
Jumbo frame configuration is saved where?
PL/SQL Export table data to .csv file and save; launch Excel inside PL/SQL and load saved .csv file
SSRS - Relationship setup in Report model
Sql Subquires
Variable not defined error using VBA ExportAsFixedFormat Type:=xlTypePDF in excel 2003
Clear Fields in Lotus Notes
Exchange Server Replication
How to get unique records based on maximum date?
SAS or SATA