ASP.net GridView not Inserting from FooterTemplate - asp.net

I'm stuck. I implemented all steps needed to insert new DB values from a checkbox and textbox controls in a GridView FooterTemplate into a SQLDataSource, but when I click my "Add" button to fire the Insert command, my page flashes and no insert occurs. As far as the actual SQL is concerned, I have a stored procedure set to the GridView's DataSource's insert action. I have separately tested the procedure and it works fine.
I based my design on this article: http://www.aspdotnetfaq.com/Faq/How-to-insert-row-in-GridView-with-SqlDataSource.aspx My error is probably somewhere in my event handlers. Any idea what I'm missing?
It would be too long to post all of the GridView code, so here are the essentials:
FooterTemplate for insert button:
<asp:GridView ID="CartonGridView" runat="server" AutoGenerateColumns="False"
CellPadding="6" DataKeyNames="CartonID" Width="100%"
DataSourceID="Carton_Table" ForeColor="#333333"
GridLines="None" AllowSorting="True">
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<Columns>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:Button ID="Button1" runat="server" CausesValidation="True"
CommandName="Update" Text="Update" />
<asp:Button ID="Button2" runat="server" CausesValidation="False"
CommandName="Cancel" Text="Cancel" />
</EditItemTemplate>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit" />
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="Button1" runat="server" CausesValidation="True"
CommandName="Insert" Text="Add" />
<asp:Button ID="Button2" runat="server" CausesValidation="False"
CommandName="Cancel" Text="Cancel" />
</FooterTemplate>
</asp:TemplateField>
...
SQLDataSource Binding to Gridview:
<asp:SqlDataSource ID="Carton_Table" runat="server"
ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
InsertCommand="spCartonInsert" InsertCommandType="StoredProcedure"
SelectCommand="spCartonSelect" SelectCommandType="StoredProcedure"
UpdateCommand="spCartonUpdate" UpdateCommandType="StoredProcedure">
...
<InsertParameters>
<asp:Parameter Name="Active" Type="Boolean" />
<asp:Parameter Name="Value" Type="String" />
<asp:Parameter Name="Description" Type="String" />
</InsertParameters>
Insertion Event Handlers:
protected void CartonGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Insert")
{
CheckBox Active = CartonGridView.FooterRow.FindControl("InsertActive") as CheckBox;
TextBox SAPCode = CartonGridView.FooterRow.FindControl("InsertSAPCode") as TextBox;
TextBox Description = CartonGridView.FooterRow.FindControl("InsertDescription") as TextBox;
SqlParameter paramActive = new SqlParameter("#Active", SqlDbType.Bit);
paramActive.Direction = ParameterDirection.Input;
paramActive.Value = Active.Checked;
insertParameters.Add(paramActive);
SqlParameter paramValue = new SqlParameter("#Value", SqlDbType.NVarChar, 30);
paramValue.Direction = ParameterDirection.Input;
paramValue.Value = paramValue.Text;
insertParameters.Add(paramValue);
SqlParameter paramDescription = new SqlParameter("#SAP_Long_Description", SqlDbType.NVarChar, 250);
paramDescription.Direction = ParameterDirection.Input;
paramDescription.Value = Description.Text;
insertParameters.Add(paramDescription);
Carton_Table.Insert();
}
}
protected void Carton_Table_Inserting(object sender, SqlDataSourceCommandEventArgs e)
{
e.Command.Parameters.Clear();
foreach (SqlParameter p in insertParameters)
e.Command.Parameters.Add(p);
}

Yep, the event-handler is not wired-up.
<asp:GridView ID="CartonGridView" runat="server" AutoGenerateColumns="False"
CellPadding="6" DataKeyNames="CartonID" Width="100%"
DataSourceID="Carton_Table" ForeColor="#333333"
GridLines="None" AllowSorting="True"
onrowcommand="CartonGridView_RowCommand">

Related

Cascading DropDownList binding in ASP.Net DetailsView templated control not working

I have two dropdown lists inside DetailsView, first dropdown DepartmentDropDown loads the data successfully from code behind using the following datasource
<asp:ObjectDataSource ID="dsDepartments" runat="server" SelectMethod="GetDepartments"
TypeName="MyCode.DepartmentEmployeeAssociations">
</asp:ObjectDataSource>
and the second dropdown EmployeeDropDown uses another datasource based on Department selection in the first dropdown (commented code works and loads the details view but not the control parameter code):
<asp:ObjectDataSource ID="dsEmployees" runat="server" SelectMethod="GetAllEmployees"
TypeName="MyCode.DepartmentEmployeeAssociations" DataObjectTypeName="Employee">
<SelectParameters>
<%--<asp:Parameter Name="deptId" Type="Int32" DefaultValue="7" />--%>
<asp:ControlParameter ControlID="DepartmentDropDown" Name="deptId" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
Here is the code in my GridView and DetailsView
<asp:Panel ID="AssociationView" runat="server" Visible="false">
<asp:GridView ID="gvAssociations" runat="server" AutoGenerateColumns="False" CssClass="GridViewStyle"
EmptyDataText="No rules defined" Width="100%" AllowPaging="True" GridLines="None"
DataKeyNames="Id" EnableModelValidation="True" DataSourceID="dsAssociations"
OnSelectedIndexChanged="gvAssociations_SelectedIndexChanged">
<Columns>
<asp:CommandField ShowSelectButton="true" SelectText="View" ItemStyle-Width="50px">
<ItemStyle Width="50px"></ItemStyle>
</asp:CommandField>
<asp:BoundField DataField="Id" HeaderText="Id" SortExpression="Id" Visible="False" />
<asp:BoundField DataField="Value1" HeaderText="Employee" SortExpression="Value1" Visible="false" />
<asp:BoundField DataField="Value1Description" HeaderText="Employee" NullDisplayText="*" />
<asp:BoundField DataField="Value2" HeaderText="Department" SortExpression="Value2" Visible="false" />
<asp:BoundField DataField="Value2Description" HeaderText="Department" NullDisplayText="*" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
<div class="DetailsContainer">
<asp:DetailsView ID="dvAssociations" runat="server" Height="50px" GridLines="None"
CellPadding="5" AutoGenerateRows="False" DataKeyNames="sId" EnableModelValidation="True"
OnItemCreated="dvAssociations_ItemCreated" OnItemUpdating="dvAssociations_ItemUpdating"
OnItemInserting="dvAssociations_ItemInserting">
<Fields>
<asp:BoundField DataField="Id" HeaderText="ID" ReadOnly="True" InsertVisible="False" Visible="false" />
<asp:TemplateField HeaderText="Department">
<ItemTemplate>
<asp:DropDownList ID="DepartmentDropDown" runat="server" SelectedValue='<%# Bind("Value2") %>'
DataSourceID="dsDepartments" DataValueField="DepartmentId" DataTextField="Name"
Enabled="false" AutoPostBack="true">
</asp:DropDownList>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="DepartmentDropDown" runat="server" SelectedValue='<%# Bind("Value2") %>'
DataSourceID="dsDepartments" DataValueField="DepartmentId" DataTextField="Name"
Enabled="true" AutoPostBack="true">
</asp:DropDownList>
</EditItemTemplate>
<InsertItemTemplate>
<asp:DropDownList ID="DepartmentDropDown" runat="server" SelectedValue='<%# Bind("Value2") %>'
DataSourceID="dsDepartments" DataValueField="DepartmentId" DataTextField="Name"
Enabled="true" AutoPostBack="true">
</asp:DropDownList>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Employee">
<ItemTemplate>
<asp:DropDownList ID="EmployeeDropDown" runat="server"
DataSourceID="dsEmployees" DataValueField="EmployeeId" DataTextField="FullName"
Enabled="false">
</asp:DropDownList>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="EmployeeDropDown" runat="server"
DataSourceID="dsEmployees" DataValueField="EmployeeId" DataTextField="FullName"
Enabled="true">
</asp:DropDownList>
</EditItemTemplate>
<InsertItemTemplate>
<asp:DropDownList ID="EmployeeDropDown" runat="server"
DataSourceID="dsEmployees" DataValueField="EmployeeId" DataTextField="FullName"
Enabled="true">
</asp:DropDownList>
</InsertItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" ShowInsertButton="True" ShowDeleteButton="True" />
</Fields>
</asp:DetailsView>
</div>
</asp:Panel>
and the code behind:
protected void gvAssociations_SelectedIndexChanged(object sender, EventArgs e)
{
dvAssociations.PageIndex = gvAssociations.SelectedRow.DataItemIndex;
}
protected void dvAssociations_ItemCreated(object sender, EventArgs e)
{
if (dvAssociations.DataItem == null)
return;
// Some checks
}
protected void dvAssociations_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
{
//some code
}
protected void dvAssociations_ItemInserting(object sender, DetailsViewUpdateEventArgs e)
{
e.NewValues["Value1"] = ((DropDownList)((DetailsView)sender).FindControl("EmployeeDropDown")).SelectedValue;
}
public List<Department> GetDepartments()
{
// code to return List<Department> departments
// other code
return departments;
}
public List<Employee> GetAllEmployees(int deptId)
{
// code to return List<Employee> employees
// other code
return employees;
}
I tried various suggestions that were given in other SO articles, but still not able to make this work. My page don't load when I have the control parameter added, but it works if I change it to a normal parameter.
<asp:ControlParameter ControlID="DepartmentDropDown" Name="deptId" PropertyName="SelectedValue" Type="Int32" />
I am not sure what it doesn't like about it, it doesn't seem to bind the data in the details view. I added the AutoPostBack to true to the first dropdown and removed the SelectedValue='<%# Bind("Value1") %>' from the second dropdown as suggested in other posts, but nothing seems to be working.
Any help would be appreciated.
I have finally made it work, it was a silly mistake but again I haven't worked on these asp components before. So, there was some learning here and hope this will help someone having similar issue.
Firstly, make sure that your data in the GridView is correct and the dropdown column has valid value and is in the dropdown list source.
Secondly, I had to move my ObjectDataSource for employees with in the itemtemplate
<asp:TemplateField HeaderText="Employee">
<ItemTemplate>
<asp:DropDownList ID="EmployeeDropDown" runat="server" SelectedValue='<%# Bind("Value1") %>'
DataSourceID="dsEmployees" DataValueField="EmployeeId" DataTextField="FullName" Enabled="false">
</asp:DropDownList>
<asp:ObjectDataSource ID="dsEmployees" runat="server" SelectMethod="GetAllEmployees"
TypeName="MyCode.DepartmentEmployeeAssociations" DataObjectTypeName="Employee">
<SelectParameters>
<asp:ControlParameter ControlID="DepartmentDropDown" Name="deptId" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="EmployeeDropDown" runat="server" SelectedValue='<%# DataBinder.Eval (Container.DataItem, "Value1") %>'
DataSourceID="dsEmployees" DataValueField="EmployeeId" DataTextField="FullName"
Enabled="true">
</asp:DropDownList>
<asp:ObjectDataSource ID="dsEmployees" runat="server" SelectMethod="GetAllEmployees"
TypeName="MyCode.DepartmentEmployeeAssociations" DataObjectTypeName="Employee">
<SelectParameters>
<asp:ControlParameter ControlID="DepartmentDropDown" Name="deptId" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
</EditItemTemplate>
<InsertItemTemplate>
<asp:DropDownList ID="EmployeeDropDown" runat="server" SelectedValue='<%# DataBinder.Eval (Container.DataItem, "Value1") %>'
DataSourceID="dsEmployees" DataValueField="EmployeeId" DataTextField="FullName"
Enabled="true">
</asp:DropDownList>
<asp:ObjectDataSource ID="dsEmployees" runat="server" SelectMethod="GetAllEmployees"
TypeName="MyCode.DepartmentEmployeeAssociations" DataObjectTypeName="Employee">
<SelectParameters>
<asp:ControlParameter ControlID="DepartmentDropDown" Name="deptId" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
</InsertItemTemplate>
</asp:TemplateField>
Also, I have replaced SelectedValue='<%# Bind("Value1") %>' to SelectedValue='<%# DataBinder.Eval (Container.DataItem, "Value1") %>' in my EmployeeDropDown aspx code to make it simpler. Which means, no need to add this event handler dvAssociations_ItemInserting to the DetailsView.
But, I have another issue related to orphan data in the grid, which doesn't exist in the dropdown - which make the ItemTemplate fail to load. That's for another post, this post is done for now. Hope it helps other.

ASP GridView DropdownList EDIT/UPDATE

I have a GridView on a ASP-Page binding to a table with foreign-keys, where the Columns have DropdownLists with TEXT gathering to the VALUES, in other Tables.
When I EDIT the Row of the GridView, I add the Text of the Dropdowns in CodeBehind. This is all working fine. But when UPDATING I am trying to set the UpdateParameters of the DataSource manually, so i want to check which values in DropDowns are selected. But in every event i tried, the dropdowns are NULL.
I have tried:
RowUpdating- and RowEditing-Events of the GridView
Updating-Event of the DataSource
ASPX:
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="False" OnRowUpdating="GridView1_RowUpdating" OnRowEditing="GridView1_RowEditing" DataSourceID="SqlDataSource1" CellPadding="4" ForeColor="#333333" GridLines="None" AllowPaging="True" AllowSorting="True" Width="90%" DataKeyNames="id" Font-Size="Large">
<Columns>
<asp:TemplateField HeaderText="id" InsertVisible="False" SortExpression="id" Visible="False">
<EditItemTemplate>
<asp:Label ID="LabelIDe" runat="server" Text='<%# Eval("id") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelIDi" runat="server" Text='<%# Bind("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Mitglied" InsertVisible="False" SortExpression="mitgliedid">
<EditItemTemplate>
<asp:Label ID="LabelMe" runat="server" Text='<%# Bind("mitgliedid") %>' Visible="false"></asp:Label>
<asp:DropDownList runat="server" ID="mitgliederDD">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelMi" runat="server" Text='<%# Bind("mitgliedid") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amt" InsertVisible="False" SortExpression="amtid">
<EditItemTemplate>
<asp:Label ID="LabelAe" runat="server" Text='<%# Bind("amtid") %>' Visible="false"></asp:Label>
<asp:DropDownList runat="server" ID="ämterDD">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelAi" runat="server" Text='<%# Bind("amtid") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowSelectButton="True" ItemStyle-HorizontalAlign="Right" />
</Columns>
<EditRowStyle BackColor="#7C6F57" HorizontalAlign="Center"></EditRowStyle>
<FooterStyle BackColor="#1C5E55" BorderStyle="None" Font-Bold="True" ForeColor="White"></FooterStyle>
<HeaderStyle BackColor="#666666" Font-Bold="True" ForeColor="White" CssClass="gridHeader"></HeaderStyle>
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" CssClass="gridPager" Font-Bold="True"></PagerStyle>
<RowStyle BackColor="#E3EAEB" HorizontalAlign="Center"></RowStyle>
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>
<SortedAscendingCellStyle BackColor="#F8FAFA"></SortedAscendingCellStyle>
<SortedAscendingHeaderStyle BackColor="#246B61"></SortedAscendingHeaderStyle>
<SortedDescendingCellStyle BackColor="#D4DFE1"></SortedDescendingCellStyle>
<SortedDescendingHeaderStyle BackColor="#15524A"></SortedDescendingHeaderStyle>
<EmptyDataTemplate>Zur Zeit kein Datensatz in dieser Tabelle !</EmptyDataTemplate>
</asp:GridView>
<asp:SqlDataSource runat="server" ID="SqlDataSource1" OnUpdating="SqlDataSource1_Updating" ConnectionString='<%$ ConnectionStrings:ConnectionStringAPPDATA %>' SelectCommand="SELECT [id], [amtid], [mitgliedid] FROM [aemter_mitglieder]" DeleteCommand="DELETE FROM [aemter_mitglieder] WHERE [id] = #id" InsertCommand="INSERT INTO [aemter_mitglieder] ([amtid], [mitgliedid]) VALUES (#amtid, #mitgliedid)" UpdateCommand="UPDATE [aemter_mitglieder] SET [amtid] = #amtid, [mitgliedid] = #mitgliedid WHERE [id] = #id">
<DeleteParameters>
<asp:Parameter Name="id" Type="Int32"></asp:Parameter>
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="amtid" Type="Int32"></asp:Parameter>
<asp:Parameter Name="mitgliedid" Type="Int32"></asp:Parameter>
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="amtid" Type="Int32"></asp:Parameter>
<asp:Parameter Name="mitgliedid" Type="Int32"></asp:Parameter>
<asp:Parameter Name="id" Type="Int32"></asp:Parameter>
</UpdateParameters>
</asp:SqlDataSource>
**
CODE BEHIND:
**
protected void SqlDataSource1_Updating(object sender, SqlDataSourceCommandEventArgs e)
{
DropDownList ämterDD = (DropDownList)GridView1.FindControl("ämterDD");
DropDownList mitgliederDD = (DropDownList)GridView1.FindControl("mitgliederDD");
if(mitgliederDD != null && ämterDD != null)
{
SqlDataSource2.UpdateParameters["amtid"].DefaultValue = ämterDD.SelectedValue;
SqlDataSource2.UpdateParameters["mitgliedid"].DefaultValue = mitgliederDD.SelectedValue;
}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DropDownList ämterDD = (DropDownList)((GridView)sender).FindControl("ämterDD");
DropDownList mitgliederDD = (DropDownList)((GridView)sender).FindControl("mitgliederDD");
if (ämterDD != null && mitgliederDD != null)
{
SqlDataSource2.UpdateParameters["amtid"].DefaultValue = ämterDD.SelectedValue;
SqlDataSource2.UpdateParameters["mitgliedid"].DefaultValue = mitgliederDD.SelectedValue;
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
DropDownList ämterDD = (DropDownList)((GridView)sender).FindControl("ämterDD");
DropDownList mitgliederDD = (DropDownList)((GridView)sender).FindControl("mitgliederDD");
if(ämterDD != null && mitgliederDD != null)
{
SqlDataSource2.UpdateParameters["amtid"].DefaultValue = ämterDD.SelectedValue;
SqlDataSource2.UpdateParameters["mitgliedid"].DefaultValue = mitgliederDD.SelectedValue;
}
}
Can anyone help me how i can set update-parameters of the GridView in code behind ?!
This code will help you to update your grid view data.
protected void GridView1_RowUpdating(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && gridView.EditIndex == e.Row.RowIndex)
{
DropDownList ddlämter = (DropDownList)e.Row.FindControl("ddlämter");
Label LabelAe = (Label)e.Row.FindControl("LabelAe");
string strValue = Convert.ToString(LabelAe.Text);
// Bind Your Drop down Here
ddlämter.DataSource = ds;
ddlämter.DataTextField = "dbRequestType";
ddlämter.DataValueField = "dbID";
ddlämter.DataBind();
ddlämter.Items.Insert(0, new ListItem("--Choose--", "0"));
if (strValue != null && strValue != "")
ddlämter .Items.FindByValue(strValue).Selected = true;
}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DropDownList ddlämter = DropDownList)gvDeliverable.Rows[e.RowIndex].FindControl("ämterDD");
SqlDataSource2.UpdateParameters["amtid"].DefaultValue = Convert.ToInt32(ddlämter.SelectedValue);
}

unable to update in gridview when require validation occur in textbox

I want to modify items in gridview by update command but in same page i have also a textbox with required validation.
i'm unable to update in gridview when require validation occur in textbox Control
And Source Code here...
<div class="row">
<asp:Button ID="Button1" runat="server" CssClass="btn btn-primary" Text="Add" OnClick="Button1_Click"
ValidationGroup="btn" />
<asp:Button ID="Button2" runat="server" CssClass="btn btn-primary" Text="Reset" OnClick="Button2_Click"
CausesValidation="False" />
<asp:Button ID="Button3" runat="server" CssClass="btn btn-primary" Text="Show" CausesValidation="False"
OnClick="Button3_Click" />
</div>
</form> </div> </div>
<asp:GridView ID="GridView1" runat="server" CssClass="table-hover table-responsive table-condensed table-bordered"
AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="id"
DataSourceID="SqlDataSource1" Visible="False">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
<asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True"
SortExpression="id" />
<asp:BoundField DataField="Loc" HeaderText="Location" SortExpression="Loc" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:mycon %>"
SelectCommand="SELECT * FROM [location]" DeleteCommand="Delete From Location Where Id=#id"
UpdateCommand="update location set loc=#loc where id=#id">
<DeleteParameters>
<asp:ControlParameter ControlID="TextBox1" Name="id" PropertyName="Text" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="loc" />
<asp:ControlParameter ControlID="GridView1" Name="id" PropertyName="SelectedValue" />
</UpdateParameters>
</asp:SqlDataSource>
and cs code here
protected void Button1_Click(object sender, EventArgs e)
{
string qry = "insert into location (loc)values(#loc) ";
SqlConnection con = Connection.Getconnection();
con.Open();
SqlCommand cmd = new SqlCommand(qry, con);
cmd.Parameters.AddWithValue("#loc", TextBox1.Text);
int x = cmd.ExecuteNonQuery();
if (x > 0)
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation!", "<script>alert('Successfully Add')</script>");
}
else
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation!", "<script>alert('Error')</script>");
}
}
protected void Button2_Click(object sender, EventArgs e)
{
TextBox1.Text = string.Empty;
}
protected void Button3_Click(object sender, EventArgs e)
{
GridView1.Visible = true;
}
Please try to add try catch for button1_click to catch Exceptions.
Validation group has an effect only when the value of the CausesValidation property is set to true.and validation group need to specify a value
Please Refer this Link

asp.net DetailsVeiw - insert a item in a dropdownlist when Insert LinkButton Selected

I am new to ASP.NET. I am trying to insert a item into a dropdownlist when click "New" to add new record. which the form will switch from ItemTemplate to InsertTempplate
Error:
"System.NullReferenceException: Object reference not set to an
instance of an object."
this code in my DetailsView.
<ItemTemplate>
<asp:Label ID="lblVendorName"
runat="Server" style="text-align:left; width:100%"
Text='<%# Eval("VendorName")%>' Width="70%"/>
</ItemTemplate>
<InsertItemTemplate>
<asp:DropDownList id="insertVendorName" datasourceid="VendorSqlDataSource"
datatextfield="VendorName" DataValueField="VendorID"
OnSelectedIndexChanged="ddlVendor_SelectedIndexChanged"
runat="server" AutoPostBack="true" />
<asp:SqlDataSource ID="VendorSqlDataSource"
ConnectionString="<%$Connectionstrings:ConnectionString%>"
SelectCommand="SELECT VendorID, VendorName
from MDF_Vendor" runat="server">
</asp:SqlDataSource>
</InsertItemTemplate>
Updated... Below is set of Link Bottons.
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnedit" runat="server"
CommandName="Edit" Text="Edit"/> |
<asp:LinkButton ID="btnInsert" runat="Server"
Text="New" CommandName="New"
OnClick="LinkButton_Click" /> |
<asp:LinkButton ID="btnDelete"
runat="server"
CommandName="Delete" Text="Delete" /> |
</ItemTemplate>
<InsertItemTemplate>
<asp:LinkButton ID="btnInsert" runat="Server"
Text="Insert" CommandName="Insert"/>
<asp:LinkButton ID="btncancel" runat="server"
CommandName="Cancel" Text="Cancel"/>
</InsertItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnupdate" runat="server"
CommandName="Update" Text="Update" />
<asp:LinkButton ID="btncancel" runat="server"
CommandName="Cancel" Text="Cancel"/>
</EditItemTemplate>
</asp:TemplateField>
I tried this code below suggested by #Aghislas (Thanks!)
protected void LinkButton_Click(object sender, EventArgs e)
{
DropDownList ddlVendor = (DropDownList)DetailsView1.FindControl("insertVendorName");
ddlVendor.Items.Insert(0, new ListItem("---Select---", "-1"));
}
Please help. Thank you.
You can try with this code
<asp:LinkButton id="LinkButton1"
Text="Click Me"
OnClick="LinkButton_Click"
runat="server"/>
protected void LinkButton_Click(Object sender, EventArgs e)
{
var ddlVendor =(DropDownList)DetailsView1.FindControl("insertVendorName");
ddlVendor.Items.Insert(0, new ListItem("---Select---", "-1"));
}
Nota : You delete code in the Page_Load and move in Click delegate

ASP.NET GridView inside UpdatePanel won't get out of Edit Mode

I have a pretty standard GridView with an SqlDataSource complete with SelectCommand/UpdateCommand/DeleteCommand.
I am utilising the Gridview's built-in commands for TemplateField'ed 's.
CommandName="Update"
CommandName="Edit"
CommandName="Cancel"
CommandName="Delete"
Everything works OK until I put the GridView inside an UpdatePanel.
1. When I click on 'edit' it goes into edit mode but won't get out of edit mode when you click Cancel or Update.
2. When I click on 'delete' performs as it should, however, I won't be able to get into edit mode anymore even if I click 'edit'
What's the matter here?
Example code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="BoxFloat">
<h4>Aliases</h4>
<hr />
<asp:SqlDataSource ID="sqlPersonAlias" runat="server"
ConnectionString="<%$ ConnectionStrings:myConnectionString %>"
ProviderName="<%$ ConnectionStrings:myConnectionString.ProviderName %>"
DeleteCommand="DELETE FROM PersonAlias WHERE PersonAliasId=?PersonAliasId"
UpdateCommand="UPDATE PersonAlias SET AliasName=?AliasName WHERE PersonAliasId=?PersonAliasId"
SelectCommand="SELECT * FROM PersonAlias E INNER JOIN Person P ON P.PersonId=E.PersonId WHERE Username=?Username">
<DeleteParameters>
<asp:Parameter Name="PersonAliasId" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="PersonAliasId" />
<asp:Parameter Name="AliasName" />
</UpdateParameters>
<SelectParameters>
<asp:QueryStringParameter Name="Username" QueryStringField="Username" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="gridviewPersonAlias" runat="server"
AutoGenerateColumns="False"
DataKeyNames="PersonAliasId"
DataSourceID="sqlPersonAlias">
<Columns>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:ImageButton ID="imagebuttonCancel" ToolTip="Cancel" CommandName="Cancel" ImageUrl="~/images/cancel16.png" runat="server" />
<asp:ImageButton ID="imagebuttonUpdate" ToolTip="Apply" OnClientClick="return confirm('Are you sure?');" CommandName="Update" ImageUrl="~/images/apply16.png" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="imagebuttonDelete" ToolTip="Delete" OnClientClick="return confirm('Are you sure?');" CommandName="Delete" ImageUrl="~/images/delete16.png" runat="server" />
<asp:ImageButton ID="imagebuttonEdit" ToolTip="Edit" CommandName="Edit" ImageUrl="~/images/edit16.png" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="AliasName" HeaderText="Alias" SortExpression="AliasName" />
</Columns>
</asp:GridView>
<hr />
<asp:TextBox ID="textboxPersonAlias" runat="server" />
<asp:Button ID="buttonPersonAliasAdd" runat="server" Text="Add" onclick="buttonPersonAliasAdd_Click" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
When "Update" is clicked, the database gets updated. It seems that the problem is just with the client-side.
Note: I'm using "?" instead of "#" for the parameters because that SqlDataSource is using MySq instead of MSSQL (I love VS2010).
I think what you need is full Postback or refresh the update Panel since it is most likely the gridview doesnt rebind
First try to put the sqldatasource outside the update panel. See if that works
I had the same problem in my project, and solved it.
here is my solution:
protected void gvPayments_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//here is the edit code
//......
//at the end add these lines:
gvPayments.EditIndex = -1;
gvPayments.DataBind();
e.Cancel = true;
}

Resources