I have a GridView that is bound to a SqlDataSource. I am running into issues with the UpdateCommand executing, it seems to be executing twice. When I step through the code in the gvChecklist_RowUpdating event, I see everything runs properly and the stored procedure is executed. I have verified the stored procedure works properly since there is a new record in the db table. When this event exits though, I get the following error:
Procedure or function usp_TestLogInsert has too many arguments
specified.
I see that the Updating event on the datasource is being called after the RowUpdating event. I have tried to cancel this event to prevent the multiple update attempts, but then nothing happens and the GridView stays in edit mode.
ASP Code
<asp:UpdatePanel ID="upGridView" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="gvChecklist" runat="server"
AutoGenerateColumns="false" DataSourceID="dsChecklist"
AutoGenerateEditButton="true"
onrowupdating="gvChecklist_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Label ID="lblStatus" runat="server"
Text='<%#Eval("Status") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddStatus" runat="server"
DataTextField="Status"
DataValueField="ID"
DataSourceID="dsStatus" />
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Division"
HeaderText="Division"
readonly="true" />
<asp:BoundField DataField="Application"
HeaderText="Application"
readonly="true" />
<asp:BoundField DataField="Task"
HeaderText="Task"
readonly="true" />
<asp:BoundField DataField="TestedBy"
HeaderText="Tested By"
readonly="true"/>
<asp:BoundField DataField="Notes"
HeaderText="Notes"
ReadOnly="false"/>
<asp:BoundField DataField="JiraTicket"
HeaderText="JIRA Ticket"
readonly="false" />
<asp:BoundField DataField="ID" />
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="gvChecklist" />
</Triggers>
</asp:UpdatePanel>
</td>
</tr>
</table>
<asp:SqlDataSource ID="dsChecklist"
SelectCommand=" SELECT l.ID, d.division, c.Context AS Application, t.Task, l.TestedBy, l.Notes, l.JiraTicket, s.Status
FROM Automation.manual.Tests t
OUTER APPLY
(SELECT TOP 1 *
FROM Automation.manual.TestLog l
WHERE l.TestID = t.ID
ORDER BY l.Date DESC) l
INNER JOIN Automation.dbo.Context c ON c.ID = t.Context
INNER JOIN Automation.dbo.Division d ON d.ID = t.Division
LEFT OUTER JOIN Automation.manual.Status s ON s.ID = l.Status"
runat="server"
ConnectionString="<%$ ConnectionStrings:AutomationDBConnectionString %>"
onupdating="dsChecklist_Updating" >
<UpdateParameters>
<asp:Parameter Name="Status" DbType="Int32" />
<asp:Parameter Name="TestID" DbType="Int32" />
<asp:Parameter Name="TestedBy" DbType="String" />
<asp:Parameter Name="Notes" DbType="String" />
<asp:Parameter Name="JiraTicket" DbType="String" />
<asp:Parameter Name="Build" DbType="String" />
</UpdateParameters>
</asp:SqlDataSource>
C#
protected void gvChecklist_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
SQLConnections sql = new SQLConnections();
SqlDataSource dsChecklist = (SqlDataSource)LoginView1.FindControl("dsChecklist");
var dd = (DropDownList)gvChecklist.Rows[e.RowIndex].FindControl("ddStatus");
var status = dd.SelectedValue;
var testID = sql.SQLSelectSingle(String.Format("SELECT ID FROM Automation.manual.Tests WHERE Task = '{0}'", (String)e.OldValues["Task"]), "pwautosql01");
string user = Page.User.Identity.Name;
string notes = (String)e.NewValues["Notes"];
string jira = (String)e.NewValues["JiraTicket"];
var dbID = e.NewValues["ID"];
string build = "TODO";
if (dbID == null) //Record does not exist in TestLog, INSERT a new one
{
dsChecklist.UpdateCommand = "[Automation].[manual].[usp_TestLogInsert]";
dsChecklist.UpdateCommandType = SqlDataSourceCommandType.StoredProcedure;
dsChecklist.UpdateParameters["Status"].DefaultValue = status;
dsChecklist.UpdateParameters["TestID"].DefaultValue = testID;
dsChecklist.UpdateParameters["TestedBy"].DefaultValue = user;
dsChecklist.UpdateParameters["Notes"].DefaultValue = notes;
dsChecklist.UpdateParameters["JiraTicket"].DefaultValue = jira;
dsChecklist.UpdateParameters["Build"].DefaultValue = build;
gvChecklist.DataBind();
}
//else //Record already exists in TestLog. UPDATE
//{
//TODO
//}
}
EDIT: I used the SQL Profiler to see what parameters are being sent in the stored procedure. Even though the INSERT occurs and a new record is created, an extra parameter called ID is being sent. I never explicitly send this parameter, but it seems that it is created since I have a BoundField called ID in my GridView.
To build on the original question, is there a way to make the UpdateCommand ignore this BoundField so it does no automatically use it as a parameter?
After using the SQL Profiler, I saw that BoundField ID was being added as an UpdateCommand Parameter implicitly. Changing this field to a TemplateItem fixes this issue.
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="tbId" Text='<%#Eval("ID") %>' ReadOnly="true" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
Related
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" DataKeyNames="IDProject" DataSourceID="SqlDataSource1" GridLines="Vertical" style="margin-top:2rem" Width="1056px">
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:TemplateField SortExpression="ProjectLeader" HeaderText="Project Leader">
<ItemTemplate>
<asp:Label Text='<%# Bind("ProjectLeader") %>' ID="lvProjectLeader" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ProjectName" HeaderText="Project Name" SortExpression="ProjectName" />
<asp:TemplateField HeaderText="Start date:" SortExpression="StartDate">
<ItemTemplate>
<asp:Label Text='<%# Bind("StartDate") %>' ID="lbStartDate" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Client Name" SortExpression="Client name">
<ItemTemplate>
<asp:Label Text='<%# Bind("Client name") %>' ID="lbClientName" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Employees">
<ItemTemplate>
<asp:Button Text="Open" ID="EmployeesOpen" OnClick="EmployeesOpen_Click" runat="server" CssClass="btn btn-outline-primary" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
InsertCommand="Insert into Project values(#ProjectName, #ClientID,#ProjectLeader,#StartDate)"
SelectCommand="select IDProject, ProjectLeader, ProjectName, StartDate, ClientID, Client.Name from Project inner join Client on IDClient = ClientID"
UpdateCommand="Update Project set ProjectName = #ProjectName where IDProject = #IDProject">
<InsertParameters>
<asp:Parameter Name="ProjectName" />
<asp:Parameter Name="ClientID" />
<asp:Parameter Name="ProjectLeader" />
<asp:Parameter Name="StartDate" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="ProjectName" />
<asp:Parameter Name="IDProject" />
</UpdateParameters>
</asp:SqlDataSource>
I made a gridview table for Projects which has values ProjectName, ClientID, ProjectLeader, StartDate and all the employees that work on that Project. Since i cant fit all the employees that work on a single project inside a small table i made a button inside that column that redirects you to another page where you can see table with all the employees. The employees are in another table in sql and i made third table which connects Projects and employees and it only contains ProjectID and EmployeeID. I have a button inside every row but i cant find a way how to make in code behind so that it takes the id of that project and prints on another page only employees that are working on that project.
public partial class Project : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void EmployeesOpen_Click(object sender, EventArgs e)
{
Response.Redirect("Employees_On_Project.aspx");
}
}
You will find what you are looking for here : https://forums.asp.net/t/1957409.aspx?Gridview+get+SelectedRow+in+button+click+event
I have a SqlDataSource connected to a GridView and I am trying to get the edit working correctly, but with everything I try I still get that parameters are not supplied.
I have tried naming the parameters with and without the '#', it seems to make no difference. As you can see in the below image, the update parameters exist and even have values!
Example image:
ASPX markup:
<asp:GridView runat="server" ID="JobGV" DataSourceID="JobApprovalsDS"
AutoGenerateColumns="False" AutoGenerateEditButton="true"
OnRowCommand="JobGV_OnRowCommand" OnRowUpdating="JobGV_OnRowUpdating">
<Columns>
<asp:BoundField HeaderText="Function" DataField="FunDesc" ReadOnly="true"/>
<asp:BoundField HeaderText="Employee" DataField="EmpName" ReadOnly="true"/>
<asp:TemplateField>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="ddlEmps" SelectedValue='<%# Eval("appEmpID")%>' DataSourceID="EmpDS" DataTextField="EmpName" DataValueField="EmpID" />
<asp:Label runat="server" ID="data" Text='<%# Eval("appBusinessUnit") +";" + Eval("appFunctID") %>' Visible="False"></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label runat="server" Text='<%# Eval("EmpName") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="JobApprovalsDS" runat="server"
ConnectionString="<%$ ConnectionStrings:JobClose %>"
SelectCommand="up_JobApprovalsSelect"
SelectCommandType="StoredProcedure"
UpdateCommand="up_JobApprovalsUpdate">
<SelectParameters>
<asp:Parameter Name="ShowAll" DefaultValue="1" />
<asp:Parameter Name="AllPhases" DefaultValue="1" />
<asp:ControlParameter Name="BusinessUnit" ControlID="ddlEditJob" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="#BusinessUnit" Type="String"/>
<asp:Parameter Name="#FunctID" Type="Int32"/>
<asp:Parameter Name="#EmpID" Type="Int32"/>
<asp:Parameter Name="#UpdateDate" Type="DateTime"/>
</UpdateParameters>
</asp:SqlDataSource>
C#:
protected void JobGV_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Update"))
{
int empid = 0;
string[] data;
int index = int.Parse(e.CommandArgument.ToString());
GridViewRow row = JobGV.Rows[index];
DropDownList ddlemp = (DropDownList) row.FindControl("ddlEmps");
empid = int.Parse(ddlemp.SelectedValue);
Label lbl = (Label) row.FindControl("data");
data = lbl.Text.Split(';');
JobApprovalsDS.UpdateParameters["#BusinessUnit"].DefaultValue = data[0];
JobApprovalsDS.UpdateParameters["#FunctID"].DefaultValue = data[1];
JobApprovalsDS.UpdateParameters["#EmpID"].DefaultValue = empid.ToString();
//JobApprovalsDS.UpdateParameters.Add("BusinessUnit", data[0]);
//JobApprovalsDS.UpdateParameters.Add("FunctID", data[1]);
//JobApprovalsDS.UpdateParameters.Add("EmpID", empid.ToString());
}
}
protected void JobGV_OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
JobApprovalsDS.Update();
}
Are you talking about the update process??
Well, in your SqlDataSource, you're not specifying that the UpdateCommand is talking to a stored procedure... you need to specify the UpdateCommandType, too! (not just the SelectCommandType)
<asp:SqlDataSource ID="JobApprovalsDS" runat="server"
ConnectionString="<%$ ConnectionStrings:JobClose %>"
SelectCommand="up_JobApprovalsSelect"
SelectCommandType="StoredProcedure"
UpdateCommand="up_JobApprovalsUpdate"
UpdateCommandType="StoredProcedure" > **** this is missing from your code!
I have a grid view with a stored procedure set up in SQL.I have three controls 2 dropdown list's and a texbox with jQuery Date picker.My problem is that the gridview isn't showing on pageload. However when I start adding the controls the gridview is suddenly displayed. From debugging, I have speculated that the textbox with the jQuery datepicker does not pass the NULL value to the stored procedure specified, though I am still wondering if it is the cause.This is the code..
Aspx Code:
<div class="datarange">
<asp:DropDownList ID="categoryDDL" AutoPostBack="true" AppendDataBoundItems="true" runat="server">
<asp:ListItem Text="Select Category" Value=" " />
</asp:DropDownList>
<asp:DropDownList ID="brokerDDL" AutoPostBack="true" runat="server"></asp:DropDownList>
<asp:TextBox ID="openDate" AutoPostBack="true" runat="server"></asp:TextBox>
</div>
<br />
<%-- SQL DATA SOURCE PARAMETERS --%>
<asp:SqlDataSource ID="SqlRAListings" runat="server" ConnectionString="<%$ ConnectionStrings:kmc_SalesPipelineConnectionString %>" SelectCommand="RecentlyAddedListings" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="categoryDDL" Name="Category" PropertyName="SelectedValue" Type="String" DefaultValue=" " />
<asp:ControlParameter ControlID="brokerDDL" Name="Broker" PropertyName="SelectedValue" Type="String" DefaultValue=" Select Employee" />
<asp:ControlParameter ControlID="openDate" Name="OpenDate" PropertyName="Text" Type="DateTime" DefaultValue="" />
</SelectParameters>
</asp:SqlDataSource>
<%-- END OF SQL DATA SOURCE PARAMETERS --%>
<%-- GRIDVIEW FOR DISPLAYING RECENTLY ADDED LISTINGS --%>
<asp:GridView ID="ralGridView" runat="server" AllowSorting="True" AutoGenerateColumns="False" OnSelectedIndexChanged="ralGridView_SelectedIndexChanged">
<Columns>
<asp:TemplateField HeaderText="Opportunity">
<ItemTemplate>
<a href="/management/opportunity.aspx?id=<%# Eval("ID") %>" target="_blank">
<%# Eval("Opportunity").ToString() != "" ? Eval("Opportunity") : "Opportunity" %>
</a>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ID" HeaderText="ID"
SortExpression="ID" InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="Category" HeaderText="Category"
SortExpression="Category" />
<asp:BoundField DataField="Contact Name" HeaderText="Contact Name"
SortExpression="Contact Name" />
<asp:BoundField DataField="Employee" HeaderText="Employee" SortExpression="Employee" />
<asp:BoundField DataField="Open Date" HeaderText="Open Date" SortExpression="Open Date" />
<asp:TemplateField HeaderText="Opportunity from">
<ItemTemplate>
<%# Eval("LeadID").ToString().Length > 0 == true ? "Lead System" : "Personal Lead" %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDbRAListings" runat="server" ConnectionString="<%$ ConnectionStrings:kmc_SalesPipelineConnectionString %>" SelectCommand="RecentlyAddedListings" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="categoryDDL" Name="Category" PropertyName="SelectedValue" Type="String" />
<asp:ControlParameter ControlID="brokerDDL" Name="Broker" PropertyName="SelectedValue" Type="String" />
<asp:ControlParameter ControlID="openDate" Name="OpenDate" PropertyName="Text" Type="DateTime" />
</SelectParameters>
</asp:SqlDataSource>
<%-- END OF GRID VIEW --%>
</form>
<script type="text/javascript">
$(function () {
var dates = $("#openDate").datepicker({
defaultDate: "+1w",
changeMonth: false,
numberOfMonths: 1
});
});
</script>
C# Code:
namespace KMCWebLMS
{
public partial class RecentlyAssignedLead : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
fillCategoryDropDown();
fillBrokerDropDown();
}
else
{
ralGridView.DataSource = SqlDbRAListings;
ralGridView.DataBind();
}
}
public void fillCategoryDropDown()
{
DataTable categories = new DataTable();
string command = #"SELECT LeadCategory FROM LeadCategory ORDER BY LeadCategory";
ConnectSQL cmd = new ConnectSQL();
SqlDataAdapter adapter = new SqlDataAdapter(cmd.configureSQL(command));
adapter.Fill(categories);
try
{
categoryDDL.DataSource = categories;
categoryDDL.DataTextField = "LeadCategory";
categoryDDL.DataValueField = "LeadCategory";
categoryDDL.DataBind();
}
catch
{
}
}
public void fillBrokerDropDown()
{
DataTable employees = new DataTable();
string command = #"SELECT TOP 100 [Emp_Name] FROM [kmc_SalesPipeline].[dbo].[vwEmployees] ORDER BY Emp_Name";
ConnectSQL cmd = new ConnectSQL();
SqlDataAdapter adapter = new SqlDataAdapter(cmd.configureSQL(command));
adapter.Fill(employees);
try
{
brokerDDL.DataSource = employees;
brokerDDL.DataTextField = "Emp_Name";
brokerDDL.DataValueField = "Emp_Name";
brokerDDL.DataBind();
}
catch
{
}
}
protected void ralGridView_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
But from your code behind , it seems you're populating the gridview only in a postback.
For PageLoad , you're only populating the dropdowns.
Shouldn't this code come
ralGridView.DataSource = SqlDbRAListings;
ralGridView.DataBind();
inside
if (!Page.IsPostBack)
I have found the solution to the problem. To do this, I declared the parameters required for the stored procedure in the Code Behind and set it there accordingly.
//STORED PROCEDURE PARAMETERS
cmd.Parameters.AddWithValue("#OpenDate", OpenDate);
cmd.Parameters.AddWithValue("#Broker", broker);
cmd.Parameters.AddWithValue("#Category", category);
The program will then display the default value on page_load displaying all the data in the gridview. On postback, the specified parameters will be set to the values that are currently stored in the specific control parameters accordingly.
broker = brokerDDL.SelectedValue;
category = categoryDDL.SelectedValue;
ralGridView.DataSource = CreateRecentlyAddedTable();
ralGridView.DataBind();
I have two tables in my database as following:
Suggestions Table: ID, Title, Description, StatusID... etc
SuggestionsStatus Table: ID, Status
I am using GridView to show the Suggestions and in the last column I put a DropDownList that for selecting the status for each Suggestion. Now, when I tried to update the Status of one of the submitted suggestions by selecting the status from the DropDownList, the value has been selected but it wasn't inserted to the Database (which means still I have NULL value in the StatusID column in the Suggestions Table) and I don't know why.
My ASP.NET code:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ID"
width="950px" CssClass="mGrid"
AlternatingRowStyle-CssClass="alt"
RowStyle-HorizontalAlign="Center"
DataSourceID="SqlDataSource1"
OnRowDataBound="GridView1_RowDataBound" >
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<HeaderStyle Font-Bold = "true" ForeColor="Black" Height="20px"/>
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="Description" HeaderText="Description"
SortExpression="Description" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Username" HeaderText="Username"
SortExpression="Username" />
<asp:BoundField DataField="DivisionShortcut" HeaderText="Division"
SortExpression="DivisionShortcut" />
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:DropDownList ID="DropDownList" runat="server" DataSourceID="SqlDataSource2"
Font-Bold="True" ForeColor="#006666" AppendDataBoundItems="false"
DataTextField="Status" DataValueField="ID" AutoPostBack="true"
OnDataBound="DropDownList_DataBound">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
SelectCommand="SELECT dbo.SafetySuggestionsLog.ID, dbo.SafetySuggestionsLog.Title, dbo.SafetySuggestionsLog.Description, dbo.employee.Name, dbo.SafetySuggestionsLog.Username,
dbo.Divisions.DivisionShortcut
FROM dbo.employee INNER JOIN
dbo.SafetySuggestionsLog ON dbo.employee.Username = dbo.SafetySuggestionsLog.Username INNER JOIN
dbo.Divisions ON dbo.employee.DivisionCode = dbo.Divisions.SapCode"
FilterExpression="[DivisionShortcut] like '{0}%'">
<FilterParameters>
<asp:ControlParameter ControlID="ddlDivision" Name="DivisionShortcut"
PropertyName="SelectedValue" Type="String" />
</FilterParameters>
</asp:SqlDataSource>
<%--For the DropDownList--%>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
SelectCommand="SELECT * FROM [SafetySuggestionsStatus]"></asp:SqlDataSource>
My code-behind:
protected void DropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
int suggestionStatus = int.Parse(ddl.SelectedValue);
//For inserting the status in the database
string connString = "Data Source=localhost\\sqlexpress;Initial Catalog=psspdbTest;Integrated Security=True";
string insertCommand = "INSERT INTO SafetySuggestionsLog (StatusID) values(#StatusID)";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(insertCommand, conn))
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#StatusID", suggestionStatus);
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
I modified the DropDownList_SelectedIndexChanged() as shown above but it gave me the following error:
Cannot insert the value NULL into column 'Title', table
'psspdbTest.dbo.SafetySuggestionsLog'; column does not allow nulls.
INSERT fails. The statement has been terminated.
So how I can fix this problem to be able to update the status of one of the submitted Suggestions in the (GridView) in the database?
I think your operation has to be done when the drop down list value changes right?
For that you have to use the OnSelectedIndexChangedmethod. When the value in the drop down changes, this method fires. Here you can write your code.
I think you didnt mention your database insert logic here.
in asp drop down list please add this
<asp:DropDownList ID="DBList" runat="server" Height="20px" Width="226px" OnSelectedIndexChanged ="DBList_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
Now write in the .cs file
protected void DBList_SelectedIndexChanged(object sender, EventArgs e)
{
// inserting into database code here
}
Find these links link1 link2
i suggest that you are trying to insert into table
that have for example 4 columns
ID, Title, Description, StatusID
you are try to insert the statusid only with ignoring all others column and error say that title column not allow null
if you want to allow it to accept null
so from table design set allow null true to title column
I am trying to delete a row from gridview on rowdataBound() event but get Procedure or function delete_row has too many arguments specified.
Below is the code
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ((e.Row != null) && (e.Row.RowType == DataControlRowType.DataRow))
{
for (int i = 0; i < GridView1.Rows.Count; i++ )
{
GridView1.Rows[i].Attributes["style"] += "cursor: pointer; cursor: hand;";
if (GridView1.DataKeys[i].Values[1].ToString() != "broken")
GridView1.Rows[i].Attributes["onclick"] =
"window.open('" + GridView1.DataKeys[i].Values[0].ToString() + "','open_window', 'menubar, toolbar, location, directories, status, scrollbars, resizable, dependent, width=640, height=480, left=0, top=0')";
else
{
GridView1.DeleteRow(i);
}
}
}
HTML mark up is below, I have 3 DataKeyNames declared is that the problem
<asp:HiddenField ID="hiddenField1" runat="server" Value="" />
<br />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:User42ConnectionString %>"
SelectCommand="lsp_show_by_letter" onselecting="SqlDataSource1_Selecting"
SelectCommandType="StoredProcedure" DeleteCommand="delete_row"
DeleteCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="hiddenField1" DefaultValue=" "
Name="letter" PropertyName="Value" Type="String" />
</SelectParameters>
<DeleteParameters>
<asp:ControlParameter Name="link_Id" ControlID="hiddenField1" PropertyName="Value" Type="Int32" />
</DeleteParameters>
</asp:SqlDataSource>
</div>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" onrowdatabound="GridView1_RowDataBound"
DataKeyNames="link_url,link_description,link_id">
<Columns>
<asp:BoundField DataField="link_display_string"
HeaderText="link_display_string" SortExpression="link_display_string" />
<asp:BoundField DataField="link_url"Visible="False" />
<asp:BoundField DataField="link_description" Visible="False" />
<asp:BoundField DataField="link_id" ReadOnly="true" Visible="False" />
</Columns>
</asp:GridView>
Delete row stored procedure is
`ALTER PROCEDURE dbo.delete_row #link_Id int AS BEGIN DELETE FROM [links] WHERE ([link_id] = #link_Id) END`
It's because your hiddenfiled is not bound to SqlDataSource and so it passes empty or null value to delete_row procedure. Since you are bounding your SQLDataSource directly to datagridview, you need to bound hideenfiled with selected row value of datagridview. This should help you trying few options but this is your base problem.