unable to update in gridview when require validation occur in textbox - asp.net

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

Related

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);
}

GridView disappears on select edit and update

I have a GridView with a sql Source, which is bound to a searchbox. The problem is that on Postback the GridView disappears. I have tried to DataBind the GridView in the PageLoad event but the problem is that the Data is coming from the searchbox so On Postback it takes out the value of the Searchbox and searches for it.
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Archiv.aspx.cs" Inherits="AutoVerwaltungASP.Archiv" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<asp:TextBox id="searchbox" Value="Search..." runat="server" ForeColor="Gray" onblur="if(this.value=='')this.value=this.defaultValue;" onfocus="if(this.value==this.defaultValue)this.value='';" />
<asp:Button Text="Suchen" runat="server" ID="btnSearch" OnClick="btnSearch_Click" Height="34px" Width="90px" Font-Size="Small"/>
<asp:Button Text="Reset" runat="server" ID="btnClear" OnClick="btnClear_Click" Height="34px" Width="90px" Font-Size="Small"/>
<cc1:AutoCompleteExtender ServiceMethod="markensuchen"
MinimumPrefixLength="2"
CompletionInterval="100" EnableCaching="false" CompletionSetCount="10"
TargetControlID="searchbox"
ID="AutoCompleteExtender1" runat="server" FirstRowSelected = "false">
</cc1:AutoCompleteExtender>
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" DataSourceID="SqlDataSourceAutos" ForeColor="Black" GridLines="Vertical" DataKeyNames="m_id" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowSelectButton="True" />
<asp:BoundField DataField="m_id" HeaderText="m_id" SortExpression="m_id" InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="m_name" HeaderText="m_name" SortExpression="m_name" />
<asp:BoundField DataField="m_h_id" HeaderText="m_h_id" SortExpression="m_h_id" />
</Columns>
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSourceAutos" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT [m_id], [m_name], [m_h_id] FROM [marke]" FilterExpression="m_name LIKE '%{0}%'" ConflictDetection="CompareAllValues" DeleteCommand="DELETE FROM [marke] WHERE [m_id] = #original_m_id AND [m_name] = #original_m_name AND [m_h_id] = #original_m_h_id" InsertCommand="INSERT INTO [marke] ([m_name], [m_h_id]) VALUES (#m_name, #m_h_id)" OldValuesParameterFormatString="original_{0}" UpdateCommand="UPDATE [marke] SET [m_name] = #m_name, [m_h_id] = #m_h_id WHERE [m_id] = #original_m_id AND [m_name] = #original_m_name AND [m_h_id] = #original_m_h_id" >
<DeleteParameters>
<asp:Parameter Name="original_m_id" Type="Int32" />
<asp:Parameter Name="original_m_name" Type="String" />
<asp:Parameter Name="original_m_h_id" Type="Int32" />
</DeleteParameters>
<FilterParameters>
<asp:ControlParameter Name="m_name" ControlID="searchbox" PropertyName="Text" />
</FilterParameters>
<InsertParameters>
<asp:Parameter Name="m_name" Type="String" />
<asp:Parameter Name="m_h_id" Type="Int32" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="m_name" Type="String" />
<asp:Parameter Name="m_h_id" Type="Int32" />
<asp:Parameter Name="original_m_id" Type="Int32" />
<asp:Parameter Name="original_m_name" Type="String" />
<asp:Parameter Name="original_m_h_id" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
public partial class Archiv : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
GridView1.DataBind();
}
}
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> markensuchen(string prefixText, int count)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select m_name from marke where " +
"m_name like #searchbox + '%'";
cmd.Parameters.AddWithValue("#searchbox", prefixText);
cmd.Connection = conn;
conn.Open();
List<string> marken = new List<string>();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
marken.Add(sdr["m_name"].ToString());
}
}
conn.Close();
return marken;
}
}
}
private string SearchString = "";
public string HighlightText(string InputTxt)
{
string Search_Str = searchbox.Text;
// Setup the regular expression and add the Or operator.
Regex RegExp = new Regex(Search_Str.Replace(" ", "|").Trim(), RegexOptions.IgnoreCase);
// Highlight keywords by calling the
//delegate each time a keyword is found.
return RegExp.Replace(InputTxt, new MatchEvaluator(ReplaceKeyWords));
}
public string ReplaceKeyWords(Match m)
{
return ("<span class=highlight>" + m.Value + "</span>");
}
protected void btnSearch_Click(object sender, EventArgs e)
{
SearchString = searchbox.Text;
}
protected void btnClear_Click(object sender, EventArgs e)
{
searchbox.Text = "";
SearchString = "";
GridView1.DataBind();
}
}
}

UpdateMethod of ObjectDataSource not reflecting in the DB on Run but works in Debugging

The Title sounds wierd but thats what is actually happening.
I found people with similar problems but there was no answer on these pages.
I have a DetailsView Control which is bound to a ObjectDataSource
Code:
<asp:DetailsView ID="DetailsView1" runat="server" BackColor="#7B7C95" BorderColor="White" BorderWidth="1px" CellPadding="2" ForeColor="White" GridLines="None" Style="height: 80%; width: 80%" AutoGenerateRows="False" DataSourceID="UserTableObjectDataSource" Font-Bold="True" Font-Names="Tahoma" AutoGenerateEditButton="True" OnItemUpdating="DetailsView1_ItemUpdating">
<AlternatingRowStyle BackColor="#393847" />
<FieldHeaderStyle VerticalAlign="Middle" />
<Fields>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<div style="width: 50%; height: auto; overflow: auto;">
<asp:Image ID="Image1" runat="server" AlternateText="No Image Added" ImageUrl='<%# Eval("ImageUrl") %>' />
</div>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" ReadOnly="True" />
<asp:BoundField DataField="PackagesBooked" HeaderText="Packages Booked" SortExpression="PackagesBooked" ReadOnly="True">
<ItemStyle Font-Underline="True" />
</asp:BoundField>
<asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
<asp:BoundField DataField="PhoneNumber" HeaderText="PhoneNumber" SortExpression="PhoneNumber" />
</Fields>
<FooterStyle BackColor="Tan" VerticalAlign="Middle" />
<HeaderStyle BackColor="Tan" Font-Bold="True" VerticalAlign="Middle" />
<PagerStyle BackColor="Silver" ForeColor="DarkSlateBlue" HorizontalAlign="Center" />
</asp:DetailsView>
<asp:ObjectDataSource ID="UserTableObjectDataSource" runat="server" SelectMethod="getUser" TypeName="HolidaysForYou.DAL.DbHandler" UpdateMethod="updateUser" ValidateRequestMode="Enabled">
<SelectParameters>
<asp:SessionParameter Name="username" SessionField="Username" Type="String" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="Email" Type="String" />
<asp:Parameter Name="PhoneNumber" Type="String" />
<asp:SessionParameter Name="username" SessionField="Username" Type="String" />
</UpdateParameters>
</asp:ObjectDataSource>
the update method looks like this
public static void updateUser(string Email, string PhoneNumber, string username)
{
string usernameLower = username.ToLower();
string queryString = "Update [UserTable] SET Email='" + Email + "',PhoneNumber='" + PhoneNumber + "' WHERE ([Name] = '" + usernameLower + "')";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
try
{
connection.Open();
command.BeginExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
}
}
When i run the program in debug mode and go slowly step by step, the program works perfectly if i just run it there is no change in the Db.
i also tried calling the updateUser function from the DetailsView1_ItemUpdating function like :
protected void DetailsView1_ItemUpdating(object sender, System.Web.UI.WebControls.DetailsViewUpdateEventArgs e)
{
try
{
string newEmail = (string)e.NewValues["Email"];
string newPhoneNumber = (string)e.NewValues["PhoneNumber"];
if (!UserHomeValidate.userUpdateValidate(newEmail, newPhoneNumber))
{
e.Cancel = true;
Error.Visible = true;
}
else
UserHomeValidate._updateUser(newEmail, newPhoneNumber, Session["Username"].ToString().ToUpper());
}
catch (Exception exception)
{
Utility.LogFile.CreateLogFile(exception);
}
}
where _updateUser is exactly the same as updateUser and still the dataBase is not changed.... this might have something to do with postback but i dont know how that works..
This is getting frustrating a lil help would be appreciated..
Solved the issue...
just had to add
if (!Page.IsPostBack)
DetailsView1.DataBind();
to the page_Load to avoid binding at the postback as then the old values will be passed...

LinqDataSource_Selecting does not work

I have used a gridview and linqdatasourse , the gridview will be fill by a linq-stored procedure after clicking a search button.
I did it like below but my grid view is empty.
It seems LinqDataSource2_Selecting does not work.
Please help what is the problem?
public void LinqDataSource2_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
_DataContext = new EDMSDataContext();
var subjectFilter = e.WhereParameters["Subject"];
var query = _DataContext.spQuickSearchDoc(subjectFilter);
e.Result = query;
}
protected void btnSearch_Click(object sender, EventArgs e)
{
_DataContext = new EDMSDataContext();
this.LinqDataSource2.WhereParameters["Subject"].DefaultValue = this.txtSearchKeywords.Text;
GridViewDocuments.Visible = false;
GridViewDocuments_Search.Visible = true;
this.GridViewDocuments_Search.DataBind();
}
Stored procedure:
ALTER PROCEDURE [dbo].[spQuickSearchDoc]
#Searchtext varchar(50)=null
AS
select DocId,DocumentNo,Title,Unit
from tblDocuments
where DocumentNo like '%'+#SearchText + '%'
or Title like '%'+#SearchText + '%'
or Unit like '%'+#SearchText + '%'
Gridview:
<asp:GridView ID="GridViewDocuments_Search" runat="server" AutoGenerateColumns=False Visible="False" onrowcommand="GridViewDocuments_Search_RowCommand"
DataKeyNames="DocID" PageSize="100" >
<Columns>
<asp:TemplateField HeaderText = "Details">
<ItemTemplate>
<asp:Button ID ="btn_Show" Text="Details" runat= "server" CommandName= "Details" CommandArgument='<%#
Container.DataItemIndex%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DocumentNo" HeaderText="DocumentNo" SortExpression="DocumentNo" />
<asp:BoundField DataField="title" HeaderText="Title" SortExpression="title" />
<asp:BoundField DataField="Docid" HeaderText="Docid" Visible="false" />
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="LinqDataSource2" runat="server"
ContextTypeName="EDMSDataContext" OnSelecting="LinqDataSource2_Selecting">
<WhereParameters>
<asp:ControlParameter Name="Subject"
ControlID="txtSearchKeywords"
PropertyName="Text"
Type="String" />
</WhereParameters>
</asp:LinqDataSource>
You need to add DataSourceID to the GridView, as in:
<asp:GridView ID="GridViewDocuments_Search" runat="server"
. . DataSourceID="LinqDataSource2">
Since it's not set, the GridView is being bound to NULL.

ASP.net GridView not Inserting from FooterTemplate

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">

Resources