Id of gridview shows wrong sequence - c#

I have a gridview which has columns (Id,Task,Reward,Time Allotted,Uploader)..I can insert data into the gridview successfully untill page no 13 with taskId 118,but after that the data starts to show up at page no 1 right after TaskId 7.
So the sequence is like ....5,6,7,119,120,121,122,8,9,10.....
So all the new data gets inserted between 7 and 8.Why is that?how can i correct this?
I don;t think this is a code fault but still here is mine:
protected void btnPost_Click(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["EasyRozMoney_ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spTasks", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Title", txtTitle.Text);
cmd.Parameters.AddWithValue("#Body", txtBody.Text);
cmd.Parameters.AddWithValue("#Reward", txtRewards.Text);
cmd.Parameters.AddWithValue("#TimeAllotted", txtTime.Text);
cmd.Parameters.AddWithValue("#PosterName", txtPoster.Text);
con.Open();
cmd.ExecuteNonQuery();
lblStatus.Text = "Task Posted Successfully.";
}
here is the gridview:
<asp:GridView ID="GridView1" runat="server" Width="936px" AllowPaging="True" AutoGenerateColumns="False" CellPadding="3" DataSourceID="SqlDataSource1" OnRowCommand="GridView1_RowCommand" style="text-align: center" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellSpacing="2" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="TaskId" HeaderText="TaskId" InsertVisible="False" ReadOnly="True" SortExpression="TaskId" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="Body" HeaderText="Body" SortExpression="Body" Visible="false" />
<asp:BoundField DataField="Reward" HeaderText="Reward(Rs)" SortExpression="Reward" />
<asp:BoundField DataField="TimeAllotted" HeaderText="Time(Min)" SortExpression="TimeAllotted" />
<asp:BoundField DataField="PosterName" HeaderText="Uploader" SortExpression="PosterName" />
<asp:ButtonField ButtonType="Button" CommandName="Select" Text="Perform Task" ControlStyle-ForeColor="White" ControlStyle-Font-Bold="true">
<ControlStyle BackColor="#CC6600" Font-Bold="True" ForeColor="White"></ControlStyle>
</asp:ButtonField>
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#CC6600" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:EasyRozMoney_ConnectionString %>" SelectCommand="SELECT * FROM [Task]"></asp:SqlDataSource>
My Table in sql is as below:
Create table Task
(
TaskId int Identity(1,1),
Title varchar(100),
Body varchar(500),
Reward decimal(4,2),
TimeAllotted int,
PosterName varchar(100)
)
my stored procedure :
Create proc spTasks
#Title varchar(100),
#Body varchar(500),
#Reward decimal(4,2),
#TimeAllotted int,
#PosterName varchar(100)
as
begin
Insert into Task values(#Title,#Body,#Reward,#TimeAllotted,#PosterName)
end

You can change the default sort on your select statement of your data source. If you want recent records to show up in the end: sort by default, if you want them to display first in your grid: sort by descending order.
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:EasyRozMoney_ConnectionString %>"
SelectCommand="SELECT * FROM [Task] ORDER BY TASKID"></asp:SqlDataSource>
On a note, you should use select '*' only in test cases. In real world scenarios, this will cause a performance blow doing a table scan. Inside your select statement, select only desired columns that are needed for display in your UI.
As others have pointed our, do check your database column that its of type int or varchar, if the later you can cast your column as an int, or better create it as an int altogether.

Related

My GridView will not populate with data from my SQL datasource

I have created a GridView that is bound to a local SQL database file (mdf). The database connection is successful. I do receive the error message from my EmptyDataText="No Data" on the webpage where the GridView is suppose to be.
Any help would be greatly appreciated.
Here is my div holding the GridView:
<div style="border: 10px hidden #0B4A80; height: 108px; width: 494px; overflow: auto; margin-bottom: 40px;" >
<asp:SqlDataSource runat="server" ID="SqlDataSource1"
ConnectionString='<%$ ConnectionStrings:DefaultConnection %>'
SelectCommand="SELECT AspNetUsers.EmailConfirmed, AspNetUser.UserName, AspNetUsers.FirstName, AspNetUsers.LastName, AspNetUsers.BusinessName, AspNetRoles.Name FROM AspNetUsers INNER JOIN AspNetRoles ON AspNetUsers.Id = AspNetRoles.Id INNER JOIN AspNetUserRoles ON AspNetUsers.Id = AspNetUserRoles.UserId AND AspNetRoles.Id = AspNetUserRoles.RoleId"></asp:SqlDataSource>
<asp:GridView ID="GridView2" runat="server" SelectMethod ="" UpdateMethod ="" AutoGenerateColumns="true" DataKeyNames="Id" EmptyDataText="No Data" EnableModelValidation="false" ForeColor="#333333" GridLines="None" BorderStyle="None" BorderWidth="10px" Height="75px" PageSize="3" Width="472px">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="Text" HeaderText="User Information" />
<asp:DynamicField DataField="EmailConfirmed" HeaderText="EmailConfirmed" SortExpression="EmailConfirmed"></asp:DynamicField>
<asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName"></asp:BoundField>
<asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName"></asp:BoundField>
<asp:DynamicField DataField="BusinessName" HeaderText="Business Name" SortExpression="BusinessName"></asp:DynamicField>
<asp:DynamicField DataField="UserName" HeaderText="Email" SortExpression="UserName"></asp:DynamicField>
<asp:DynamicField DataField="Name" HeaderText="Role" SortExpression="Role" ></asp:DynamicField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#D7E4FF" Font-Bold="True" ForeColor="#1484AA" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
</asp:GridView>
</div>
Here is my Code behind:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid1();
BindGrid2();
}
private void BindGrid2()
{
String queryString = "SELECT [EmailConfirmed], [UserName], [FirstName], [LastName], [BusinessName], [Name] FROM AspNetUsers INNER JOIN AspNetRoles ON AspNetUsers.Id = AspNetRoles.Id INNER JOIN AspNetUserRoles ON AspNetUsers.Id = AspNetUserRoles.UserId AND AspNetRoles.Id = AspNetUserRoles.RoleId";
DataSet ds = GetData(queryString);
if (ds.Tables.Count > 0)
{
GridView2.DataSource = ds;
GridView2.DataBind();
}
else
{
Response.Write("Unable to conenct to the database");
}
}
DataSet GetData(String queryString)
{
//Retrive the connection string in the web.config file.
String connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
DataSet ds = new DataSet();
try
{
// Connect to the database and run query.
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
//Fill the dataSet.
adapter.Fill(ds);
}
catch(System.Exception ex)
{
// The connection failed. Display an error message.
Response.Write("Unable to connect to the database.");
Response.Write(ex.Message);
}
return ds;
}
}
}
Please remove your code-behind database calls. You are already populating the gridview from the ASPX page's SQL data source.
ASPX:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Id" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" ReadOnly="True" SortExpression="Id" />
<asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
<asp:CheckBoxField DataField="EmailConfirmed" HeaderText="EmailConfirmed" SortExpression="EmailConfirmed" />
<asp:BoundField DataField="PasswordHash" HeaderText="PasswordHash" SortExpression="PasswordHash" />
<asp:BoundField DataField="SecurityStamp" HeaderText="SecurityStamp" SortExpression="SecurityStamp" />
<asp:BoundField DataField="PhoneNumber" HeaderText="PhoneNumber" SortExpression="PhoneNumber" />
<asp:CheckBoxField DataField="PhoneNumberConfirmed" HeaderText="PhoneNumberConfirmed" SortExpression="PhoneNumberConfirmed" />
<asp:CheckBoxField DataField="TwoFactorEnabled" HeaderText="TwoFactorEnabled" SortExpression="TwoFactorEnabled" />
<asp:BoundField DataField="LockoutEndDateUtc" HeaderText="LockoutEndDateUtc" SortExpression="LockoutEndDateUtc" />
<asp:CheckBoxField DataField="LockoutEnabled" HeaderText="LockoutEnabled" SortExpression="LockoutEnabled" />
<asp:BoundField DataField="AccessFailedCount" HeaderText="AccessFailedCount" SortExpression="AccessFailedCount" />
<asp:BoundField DataField="UserName" HeaderText="UserName" SortExpression="UserName" />
<asp:BoundField DataField="TrialExpiration" HeaderText="TrialExpiration" SortExpression="TrialExpiration" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
</Columns>
</asp:GridView>
<asp:SqlDataSource runat="server" ID="SqlDataSource1"
ConnectionString='......' SelectCommand="SELECT AspNetUsers.EmailConfirmed, AspNetUser.UserName, AspNetUsers.FirstName, AspNetUsers.LastName, AspNetUsers.BusinessName, AspNetRoles.Name FROM AspNetUsers LEFT OUTER JOIN AspNetUserRoles ON AspNetUsers.Id = AspNetUserRoles.UserId LEFT OUTER JOIN AspNetRoles ON AspNetRoles.Id = AspNetUserRoles.RoleId"></asp:SqlDataSource>
C# code-behind:
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
}
}
Did you forget to open the connection?
using(SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
//Fill the dataSet.
adapter.Fill(ds);
}

Retrieving data from DetailsView

I'm trying to retrieve data from the DetailsView control in order to input them into another database table. I've looked through other questions that others asked but none of their questions could fit into my situation, which is trying to access SQL Database. Ultimately, I couldn't find the answer I require.
Basically, my objective of the codes is to extract the second row of the DetailsView, since the first row are mostly the static headers that do not change. My DetailsView would change upon the selection of a GridView above. Hence, I'm trying to retrieve the data on the second row, explaining my usage of Rows[2] , while I presume that "Cells[]" refers to the columns.
I'm using the following codes to do so.
string insertQuery = "insert into SalesOrders ([pQuotation#], pServices, pQty, pDescription, [p[Price/Unit]], pNetvalue, pProgress, pClientNo values (#quotationno,#services,#quantity,#description,#priceperunit,#netvalue,#progress,#clientno)";
cmd = new SqlCommand(insertQuery, con)
cmd.Parameters.AddWithValue("#quotationno", DetailsView1.Rows[0].Cells[1].Text);
cmd.Parameters.AddWithValue("#services", DetailsView1.Rows[1].Cells[1].Text);
cmd.Parameters.AddWithValue("#quantity", DetailsView1.Rows[2].Cells[1].Text);
cmd.Parameters.AddWithValue("#description", DetailsView1.Rows[3].Cells[1].Text);
cmd.Parameters.AddWithValue("#priceperunit", DetailsView1.Rows[4].Cells[1].Text);
cmd.Parameters.AddWithValue("#netvalue", DetailsView1.Rows[5].Cells[1].Text);
cmd.Parameters.AddWithValue("#progress", "0%");
cmd.Parameters.AddWithValue("#clientno", clientnolbl.Text.ToString());
I've been thrown the following exception:
Error:System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: index at System.Web.UI.ControlCollection.get_Item(Int32 index) at RealClientPurchase.Button1_Click(Object sender, EventArgs e) in d:\Desktop\RealClientPurchase.aspx.cs:line 27
EDIT:
This is the code behind file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class RealClientPurchase : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
clientnolbl.Text = Session["sClientNo"].ToString();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\Desktop\TemporarySter\App_Data\legitdatabase.mdf;Integrated Security=True;Connect Timeout=30");
try
{
con.Open();
SqlCommand cmd;
string insertQuery = "insert into SalesOrders ([pQuotation#], pServices, pQty, pDescription, [p[Price/Unit]], pNetvalue, pProgress, pClientNo values (#quotationno,#services,#quantity,#description,#priceperunit,#netvalue,#progress,#clientno)";
cmd = new SqlCommand(insertQuery, con);
cmd.Parameters.AddWithValue("#quotationno", DetailsView1.Rows[0].Cells[1].Text);
cmd.Parameters.AddWithValue("#services", DetailsView1.Rows[1].Cells[1].Text);
cmd.Parameters.AddWithValue("#quantity", DetailsView1.Rows[2].Cells[1].Text);
cmd.Parameters.AddWithValue("#description", DetailsView1.Rows[3].Cells[1].Text);
cmd.Parameters.AddWithValue("#priceperunit", DetailsView1.Rows[4].Cells[1].Text);
cmd.Parameters.AddWithValue("#netvalue", DetailsView1.Rows[5].Cells[1].Text);
cmd.Parameters.AddWithValue("#progress", "0%");
cmd.Parameters.AddWithValue("#clientno", clientnolbl.Text.ToString());
ScriptManager.RegisterStartupScript(this, this.GetType(), "redirect",
"alert('Purchase order has been submitted! Kindly proceed to checkout.'); window.location='" +
Request.ApplicationPath + "CurrentCheckout.aspx';", true);
con.Close();
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
}
These are the aspx codes:
<%# Page Title="" Language="C#" MasterPageFile="~/ClientPortal.master" AutoEventWireup="true" CodeFile="RealClientPurchase.aspx.cs" Inherits="RealClientPurchase" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Register1ConnectionString %>" SelectCommand="SELECT [qQuotationNo], [qServices], [qQuantity], [qDate] FROM [Quotations] WHERE ([qClientNo] = #qClientNo)">
<SelectParameters>
<asp:SessionParameter Name="qClientNo" SessionField="sClientNo" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:Register1ConnectionString %>" SelectCommand="SELECT [qQuotationNo], [qServices], [qQuantity], [qDescription], [qPricePerQty], [qTotalPayable] FROM [Quotations] WHERE ([qQuotationNo] = #qQuotationNo)">
<SelectParameters>
<asp:ControlParameter ControlID="GridView1" Name="qQuotationNo" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:Label ID="clientnolbl" runat="server" Text="Label" Visible="False"></asp:Label>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="qQuotationNo" DataSourceID="SqlDataSource1" Height="125px" Width="452px" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="qQuotationNo" HeaderText="Quotation No" InsertVisible="False" ReadOnly="True" SortExpression="qQuotationNo" />
<asp:BoundField DataField="qServices" HeaderText="Services" SortExpression="qServices" />
<asp:BoundField DataField="qQuantity" HeaderText="Quantity" SortExpression="qQuantity" />
<asp:BoundField DataField="qDate" HeaderText="Date" SortExpression="qDate" />
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" DataSourceID="SqlDataSource2" Height="50px" Width="452px" CellPadding="4" ForeColor="#333333" GridLines="None" DataKeyNames="qQuotationNo">
<AlternatingRowStyle BackColor="White" />
<CommandRowStyle BackColor="#D1DDF1" Font-Bold="True" />
<EditRowStyle BackColor="#2461BF" />
<FieldHeaderStyle BackColor="#DEE8F5" Font-Bold="True" />
<Fields>
<asp:BoundField DataField="qQuotationNo" HeaderText="qQuotationNo" SortExpression="qQuotationNo" InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="qServices" HeaderText="qServices" ReadOnly="True" SortExpression="qServices" />
<asp:BoundField DataField="qQuantity" HeaderText="qQuantity" SortExpression="qQuantity" ReadOnly="True" />
<asp:BoundField DataField="qDescription" HeaderText="qDescription" SortExpression="qDescription" ReadOnly="True" />
<asp:BoundField DataField="qPricePerQty" HeaderText="qPricePerQty" SortExpression="qPricePerQty" ReadOnly="True" />
<asp:BoundField DataField="qTotalPayable" HeaderText="qTotalPayable" SortExpression="qTotalPayable" ReadOnly="True" />
</Fields>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
</asp:DetailsView>
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />
<br />
<br />
<br />
</asp:Content>
I've found the solution.
I changed the fields in the database table to exclude "#" and "[" or "]"
It appears these signs do not function well in a SQL statement.
Revamped codes are as follows, and they do work.
SqlCommand cmd;
string insertQuery = "INSERT INTO SalesOrders (pQuotationNo, pServices, pQty, pDescription, pPricePerQty, pNetvalue, pProgress, pClientNo) values (#quotationno,#services,#quantity,#description,#priceperunit,#netvalue,#progress,#clientno)";
cmd = new SqlCommand(insertQuery, con);
cmd.Parameters.AddWithValue("#quotationno", DetailsView1.Rows[0].Cells[1].Text.ToString());
cmd.Parameters.AddWithValue("#services", DetailsView1.Rows[1].Cells[1].Text.ToString());
cmd.Parameters.AddWithValue("#quantity", DetailsView1.Rows[2].Cells[1].Text.ToString());
cmd.Parameters.AddWithValue("#description", DetailsView1.Rows[3].Cells[1].Text.ToString());
cmd.Parameters.AddWithValue("#priceperunit", DetailsView1.Rows[4].Cells[1].Text.ToString());
cmd.Parameters.AddWithValue("#netvalue", DetailsView1.Rows[5].Cells[1].Text.ToString());
cmd.Parameters.AddWithValue("#progress", "0%");
cmd.Parameters.AddWithValue("#clientno", clientnolbl.Text.ToString());
cmd.ExecuteNonQuery();
Can you try DetailsView1.Rows[0].Cells[0].Text?
Since your DetailsView has BoundFields only, this should work.
Regards

How to get a refreshed table without refreshing the whole page?

I am developing an ASP.NET intranet web application which is a Quiz Engine. Since I am a new ASP.NET developer, I have a table that shows some feedback received from the users and the admin has the ability to accept or reject these feedback using the DropDownList.
Under this table, there is a JQuery Accordion that when the Admin clicks on it, he will see a table with the received feedback for the last three months. But when the admin accepts or rejects one of the feedback and then clicks on the Accordion, he will see the that table but without that feedback even if the feedback is one of the feedbacks submitted last month. However, when you refresh the page and then clicks on the Accordion, he will see it.
So is there any functionality that will help me to get an auto-refresh table with refreshing the whole page?
Any help please?
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" OnSelectedIndexChanged ="DropDownList_SelectedIndexChanged">
</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>
<%--Filtering by Division--%>
<asp:SqlDataSource ID="sqlDataSourceDivision" runat="server"
ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
SelectCommand="SELECT [DivisionShortcut] FROM [Divisions]"></asp:SqlDataSource>
<dl id="jfaq">
<br />
<dt>Safety Suggestions List (for the last three months)</dt>
<dd>
<br />
<asp:Panel ID="Panel1" runat="server">
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
AllowSorting="True" CssClass="mGrid"
AlternatingRowStyle-CssClass="alt"
RowStyle-HorizontalAlign="Center"
DataSourceID="SqlDataSource4">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<HeaderStyle Font-Bold = "true" ForeColor="Black" Height="20px"/>
<Columns>
<asp:BoundField DataField="SubmittedMonth" HeaderText="Submitted Month"
SortExpression="SubmittedMonth" ReadOnly="True" />
<asp:BoundField DataField="DivisionShortcut" HeaderText="Division"
SortExpression="DivisionShortcut" />
<asp:BoundField DataField="Username" HeaderText="Username"
SortExpression="Username" />
<asp:BoundField DataField="Name" HeaderText="Name"
SortExpression="Name" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="Description" HeaderText="Description"
SortExpression="Description" />
<asp:BoundField DataField="Type" HeaderText="Type" SortExpression="Type" />
<asp:BoundField DataField="Status" HeaderText="Status"
SortExpression="Status" />
</Columns>
<RowStyle HorizontalAlign="Center"></RowStyle>
</asp:GridView>
</asp:Panel>
<asp:SqlDataSource ID="SqlDataSource4" runat="server"
ConnectionString="<%$ ConnectionStrings:testConnectionString %>" SelectCommand="SELECT TOP (100) PERCENT LEFT(DATENAME(month, dbo.SafetySuggestionsLog.DateSubmitted), 3) + '-' + DATENAME(year, dbo.SafetySuggestionsLog.DateSubmitted)
AS SubmittedMonth, dbo.Divisions.DivisionShortcut, dbo.SafetySuggestionsLog.Username, dbo.employee.Name, dbo.SafetySuggestionsLog.Title,
dbo.SafetySuggestionsLog.Description, dbo.SafetySuggestionsType.Type, dbo.SafetySuggestionsStatus.Status
FROM dbo.Divisions INNER JOIN
dbo.employee ON dbo.Divisions.SapCode = dbo.employee.DivisionCode INNER JOIN
dbo.SafetySuggestionsLog ON dbo.employee.Username = dbo.SafetySuggestionsLog.Username INNER JOIN
dbo.SafetySuggestionsType ON dbo.SafetySuggestionsLog.TypeID = dbo.SafetySuggestionsType.ID INNER JOIN
dbo.SafetySuggestionsStatus ON dbo.SafetySuggestionsLog.StatusID = dbo.SafetySuggestionsStatus.ID
WHERE (DATEDIFF(month, dbo.SafetySuggestionsLog.DateSubmitted, GETDATE()) < 3)
ORDER BY dbo.SafetySuggestionsLog.DateSubmitted DESC">
</asp:SqlDataSource>
<asp:Button ID="btnPrint" runat="server" Text="Print" OnClick="btnPrint_Click" />
</dd>
</dl>
Code-Behind:
protected void DropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
int suggestionStatus = int.Parse(ddl.SelectedValue);
GridViewRow row = (GridViewRow)ddl.NamingContainer;
string strID = GridView1.DataKeys[row.RowIndex]["ID"].ToString();
int ID = Int32.Parse(strID);
//For inserting the status in the database
string connString = "Data Source=localhost\\sqlexpress;Initial Catalog=psspdbTest;Integrated Security=True";
string updateCommand = "UPDATE SafetySuggestionsLog SET [StatusID] = #StatusID WHERE [ID] = #ID";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(updateCommand, conn))
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#StatusID", suggestionStatus);
cmd.Parameters.AddWithValue("#ID", ID);
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
UPDATE:
I used the UpdatePanel control to get a partial update, and I used <triggers>, but I got the following error and I don't know why:
Could not find an event named 'Click' on associated control
'GridView2' for the trigger in UpdatePanel 'UpdatePanel1'.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="GridView2" EventName="Click" />
</Triggers>
<ContentTemplate>
<dl id="jfaq">
<br />
<dt>Safety Suggestions List (for the last three months)</dt>
<dd>
<br />
<asp:Panel ID="Panel1" runat="server">
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
AllowSorting="True" CssClass="mGrid"
AlternatingRowStyle-CssClass="alt"
RowStyle-HorizontalAlign="Center"
DataSourceID="SqlDataSource4">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<HeaderStyle Font-Bold = "true" ForeColor="Black" Height="20px"/>
<Columns>
<asp:BoundField DataField="SubmittedMonth" HeaderText="Submitted Month"
SortExpression="SubmittedMonth" ReadOnly="True" />
<asp:BoundField DataField="DivisionShortcut" HeaderText="Division"
SortExpression="DivisionShortcut" />
<asp:BoundField DataField="Username" HeaderText="Username"
SortExpression="Username" />
<asp:BoundField DataField="Name" HeaderText="Name"
SortExpression="Name" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="Description" HeaderText="Description"
SortExpression="Description" />
<asp:BoundField DataField="Type" HeaderText="Type" SortExpression="Type" />
<asp:BoundField DataField="Status" HeaderText="Status"
SortExpression="Status" />
</Columns>
<RowStyle HorizontalAlign="Center"></RowStyle>
</asp:GridView>
</asp:Panel>
<asp:SqlDataSource ID="SqlDataSource4" runat="server"
ConnectionString="<%$ ConnectionStrings:testConnectionString %>" SelectCommand="SELECT TOP (100) PERCENT LEFT(DATENAME(month, dbo.SafetySuggestionsLog.DateSubmitted), 3) + '-' + DATENAME(year, dbo.SafetySuggestionsLog.DateSubmitted)
AS SubmittedMonth, dbo.Divisions.DivisionShortcut, dbo.SafetySuggestionsLog.Username, dbo.employee.Name, dbo.SafetySuggestionsLog.Title,
dbo.SafetySuggestionsLog.Description, dbo.SafetySuggestionsType.Type, dbo.SafetySuggestionsStatus.Status
FROM dbo.Divisions INNER JOIN
dbo.employee ON dbo.Divisions.SapCode = dbo.employee.DivisionCode INNER JOIN
dbo.SafetySuggestionsLog ON dbo.employee.Username = dbo.SafetySuggestionsLog.Username INNER JOIN
dbo.SafetySuggestionsType ON dbo.SafetySuggestionsLog.TypeID = dbo.SafetySuggestionsType.ID INNER JOIN
dbo.SafetySuggestionsStatus ON dbo.SafetySuggestionsLog.StatusID = dbo.SafetySuggestionsStatus.ID
WHERE (DATEDIFF(month, dbo.SafetySuggestionsLog.DateSubmitted, GETDATE()) < 3)
ORDER BY dbo.SafetySuggestionsLog.DateSubmitted DESC">
</asp:SqlDataSource>
<asp:Button ID="btnPrint" runat="server" Text="Print" OnClick="btnPrint_Click" />
</dd>
</dl>
</ContentTemplate>
</asp:UpdatePanel>
In the trigger you mentioned Click event, but in the code behind you have only DropDownList_SelectedIndexChanged event.
Instead you can trigger the SelectedIndexChanged event for the DropDownList as
<asp:AsyncPostBackTrigger ControlID="DropDownList" EventName="SelectedIndexChanged" />
You just need to trigger a valid event in the code behind.
Update: Since the SelectedIndexChanged updates the database, so you need to refresh the DataGrid to populate the updated data.
Add this line code at the end of SelectedIndexChanged method:
GridView2.DataBind();
use ajax update panel this may help http://ajax.net-tutorials.com/controls/updatepanel-control/

How to update/insert the status of one of the submitted suggestions in GridView by selecting a value from DropDownList?

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

How to show the user's selected value as a letter not as a number?

The web application that I am developing right now has something called quiz engine which provides users with short quizzes which consist of one question or more. Now, I have a problem with the RESULTS page that shows in a GridView the
Question Number, User's Answer and Result. Also this page shows in a DetailsView the Question, four possible answers, correct answer and the answer explanation. The main problem that I have is following:
I set the Correct Answer in the database to nvarchar datatype. and I listed the possble answers as A, B, C and D when the user chooses one of them (for example C), the GridView will show the result (the user's answer) as a number which is 3 not as a letter, while the DetailsView will show the Correct Answer as C. I don't know why.
For creating the Quiz engine, I used the Toturial in the ASP.NET website for creating it.
My ASP.NET code:
<asp:GridView ID="resultGrid" runat="server" DataKeyNames="QuestionID" SelectedIndex="0"
AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" AutoGenerateSelectButton="True" OnSelectedIndexChanged="resultGrid_SelectedIndexChanged" Width="555px">
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" CssClass="generaltext" HorizontalAlign="Center" />
<Columns>
<asp:BoundField DataField="QuestionID" HeaderText="Question" />
<%--<asp:BoundField DataField="CorrectAnswer" HeaderText="Correct Answer" />--%>
<asp:BoundField DataField="UserAnswer" HeaderText="Your Answer" />
<asp:BoundField DataField="Result" HeaderText="Result" />
</Columns>
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" CssClass="boldtext" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
SelectCommand="SELECT [Question], [Answer1], [Answer2], [Answer3], [QuestionID], [QuestionOrder], [Answer4], [CorrectAnswer], [AnswerExplanation], [QuizID] FROM [Question] WHERE ([QuizID] = #QuizID) ORDER BY [QuestionOrder]">
<SelectParameters>
<asp:SessionParameter Name="QuizID" SessionField="QuizID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:DetailsView ID="answerDetails" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" Height="45px" Width="552px" DataSourceID="SqlDataSource1"
AutoGenerateRows="False" DataKeyNames="QuestionID">
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<CommandRowStyle BackColor="#E2DED6" Font-Bold="True" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" CssClass="generaltext" />
<FieldHeaderStyle BackColor="#E9ECF1" Font-Bold="True" CssClass="boldtext" Width="100px" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Fields>
<asp:BoundField DataField="Question" HeaderText="Question"
SortExpression="Question" />
<asp:BoundField DataField="Answer1" HeaderText="A"
SortExpression="Answer1" />
<asp:BoundField DataField="Answer2" HeaderText="B"
SortExpression="Answer2" />
<asp:BoundField DataField="Answer3" HeaderText="C"
SortExpression="Answer3" />
<asp:BoundField DataField="Answer4" HeaderText="D"
SortExpression="Answer4" />
<asp:BoundField DataField="CorrectAnswer" HeaderText="Correct Answer"
SortExpression="CorrectAnswer" HeaderStyle-BackColor="lightgreen" />
<asp:BoundField DataField="AnswerExplanation" HeaderText="Explanation"
SortExpression="AnswerExplanation" HeaderStyle-BackColor="lightgreen" />
</Fields>
</asp:DetailsView>
My code-behind:
protected void Page_Load(object sender, EventArgs e)
{
ArrayList al = (ArrayList)Session["AnswerList"];
if (al == null)
{
Response.Redirect("default.aspx");
}
resultGrid.DataSource = al;
resultGrid.DataBind();
// Save the results into the database.
if (IsPostBack == false)
{
// Calculate score
double questions = al.Count;
double correct = 0.0;
for (int i = 0; i < al.Count; i++)
{
Answer a = (Answer)al[i];
if (a.Result == Answer.ResultValue.Correct)
correct++;
}
double score = (correct / questions) * 100;
string username = HttpContext.Current.User.Identity.Name.ToString().Replace("ARAMCO\\", "");
SqlDataSource userQuizDataSource = new SqlDataSource();
userQuizDataSource.ConnectionString = ConfigurationManager.ConnectionStrings["testConnectionString"].ToString();
userQuizDataSource.InsertCommand = "INSERT INTO [UserQuiz] ([QuizID], [DateTimeComplete], [Score], [Username]) VALUES (#QuizID, #DateTimeComplete, #Score, #Username)";
userQuizDataSource.InsertParameters.Add("QuizID", Session["QuizID"].ToString());
userQuizDataSource.InsertParameters.Add("DateTimeComplete", DateTime.Now.ToString());
userQuizDataSource.InsertParameters.Add("Score", score.ToString());
userQuizDataSource.InsertParameters.Add("Username", username);
int rowsAffected = userQuizDataSource.Insert();
if (rowsAffected == 0)
{
// Let's just notify that the insertion didn't
// work, but let' s continue on ...
errorLabel.Text = "There was a problem saving your quiz results into our database. Therefore, the results from this quiz will not be displayed on the list on the main menu.";
}
}
}
protected void resultGrid_SelectedIndexChanged(object sender, EventArgs e)
{
SqlDataSource1.FilterExpression = "QuestionOrder=" + resultGrid.SelectedValue;
}
SO HOW TO FIX THIS PROBLEM?
You have to fetch all question and Answer in One datatable/ Array List.
And then bind it in form one by one. Suppose you are in First question and it's Correct answer is D then and user select B that time flag for first question is false. And if it's answer is correct then set flag to true. do this process in all question. After finishing exam you can create result using that flag.
I think you have to maintain array for Question and answer.For Eg. You have to create array for Question,answer and Selected Answer. When User change option and submit that time check selected option is right or Wrong. If selected Answer is correct then set flag (Selected Answer) to true. And After completion of Exam you have to generate result using that Array.
I have also done this application using this way....
May be this help to you...
If you have any query then ask me.....

Categories

Resources