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);
}
Related
I'd like to send gridview rows to an email on button press. The number of rows selected vary and use check boxes.
Background:
The app consists of 2 GridViews. One acts as a schedule, the other acts as a holding area for items taken out of the schedule. Included below is what I use to move Items out of the schedule. The code to put items back into schedule is identical, so it was not included.
The email function is to notify the user what specific items were taken out/put into schedule.
GridView1
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" DataKeyNames="ID" AllowPaging="True" ShowHeaderWhenEmpty="True" BackColor="White" BorderColor="#003399" BorderStyle="None" BorderWidth="1px" CellPadding="4" OnPageIndexChanging="GridView1_PageIndexChanging" Width="450px">
<Columns>
<asp:BoundField DataField="VEH_SER_NO" SortExpression="VEH_SER_NO" ReadOnly="True">
<ItemStyle HorizontalAlign="Center" Width="75px" Wrap="False" />
</asp:BoundField>
<asp:BoundField DataField="DATE_BLD_RATE" SortExpression="DATE_BLD_RATE" ReadOnly="True" DataFormatString="{0:yyyy/MM/dd}">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="SEQ" SortExpression="SEQ" ReadOnly="True">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="SV_TYPE_CD" SortExpression="SV_TYPE_CD" ReadOnly="True" Visible="False" />
<asp:BoundField DataField="COMMENT" SortExpression="COMMENT" Visible="False" ReadOnly="False" />
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkSel" runat="server" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#99CCCC" ForeColor="White" HorizontalAlign="center" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<SortedAscendingCellStyle BackColor="#EDF6F6" />
<SortedAscendingHeaderStyle BackColor="#0D4AC4" />
<SortedDescendingCellStyle BackColor="#D6DFDF" />
<SortedDescendingHeaderStyle BackColor="#002876" />
</asp:GridView>
Code:
protected void cmdMoveRight_Click(object sender, EventArgs e)
{
if (drpReason0.SelectedValue != "" && drpReason.SelectedValue != "")
{
string strSQL = "SELECT VEH_SER_NO, DATE_BLD_RATE, SEQ, SV_TYPE_CD, COMMENT FROM Schedule " +
"WHERE Schedule.id = #ID";
MoveRows(GridView1, strSQL);
}
}
void MoveRows(GridView gv, string strSQL)
{
foreach (GridViewRow OneRow in gv.Rows)
{
CheckBox ckBox = OneRow.FindControl("cHkSel") as CheckBox;
if (ckBox.Checked)
{
int PKID = (int)gv.DataKeys[OneRow.RowIndex]["ID"];
SqlCommand cmdSQL = new SqlCommand(strSQL);
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PKID;
SqlRun(cmdSQL);
}
}
LoadGrids();
}
public void SqlRun(SqlCommand cmdSQL)
{
using (SqlConnection conn = new SqlConnection(cs))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
cmdSQL.ExecuteNonQuery();
}
}
}
I have two gridviews each with their own table.
I'm trying to make it so I can select a row(s) from GridViewA and move it to GridViewB (not copy). Then be able to move the selected row(s) from GridViewB back to GridViewA.
GridViewA (populated with SqlDataSource1)
<asp:GridView ID="grdA" runat="server" CellPadding="4" AllowPaging="True" AutoGenerateColumns="False" ShowHeaderWhenEmpty="True" DataKeyNames="ID" DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="Vertical" Width="75%">
<AlternatingRowStyle BackColor="white" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True"/>
<asp:BoundField DataField="Data1"HtmlEncode="false"/>
<asp:BoundField DataField="Data2" HtmlEncode="false"/>
<asp:BoundField DataField="Data3" HtmlEncode="false"/>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkBox" runat="server" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
GridViewB (populated with SqlDataSource2)
<asp:GridView ID="grdB" runat="server" CellPadding="4" AllowPaging="True" AutoGenerateColumns="False" ShowHeaderWhenEmpty="True" DataKeyNames="ID" DataSourceID="SqlDataSource2" ForeColor="#333333" GridLines="Vertical" Width="75%">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True"/>
<asp:BoundField DataField="Data1"HtmlEncode="false"/>
<asp:BoundField DataField="Data2" HtmlEncode="false"/>
<asp:BoundField DataField="Data3" HtmlEncode="false"/>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkBox2" runat="server" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
Button to move row(s) from GridViewA to GridViewB. It works but I'm not sure how to delete the row from GridViewA after moving to GridViewB
protected void btnSubmit_Click(object sender, EventArgs e)
{
string DataA, DataB, DataC;
var connectionString = ConfigurationManager.ConnectionStrings["Database1"].ConnectionString;
var insertStatement = "INSERT INTO SqlTableB (Data1, Data2, Data3) VALUES (#Data1, Data2, Data3)";
using (var sqlConnection = new SqlConnection(connectionString))
foreach (GridViewRow gRow in grdA.Rows)
{
CheckBox cb = (gRow.FindControl("chkBox") as CheckBox);
if (cb.Checked)
{
DataA = Convert.ToString(gRow.Cells[1].Text);
DataB = Convert.ToString(gRow.Cells[2].Text);
DataC = Convert.ToString(gRow.Cells[3].Text);
using (var sqlCommand = new SqlCommand(insertStatement, sqlConnection))
{
sqlConnection.Open();
sqlCommand.Parameters.AddWithValue("#Data1", DataA);
sqlCommand.Parameters.AddWithValue("#Data2", DataB);
sqlCommand.Parameters.AddWithValue("#Data3", DataC);
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
}
}
}
}
Please let me know if I can make the issue more clear, thank you
I would approach the problem this way:
First, make sure you set the PK row id for the Grid (that way you dont have to include in the display, or markup).
So USE "datakeys" setting of the grid - this will help a lot.
So, say two grids, like this:
<div style="float:left;width: 40%">
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" DataKeyNames="ID" cssclass="table">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" SortExpression="HotelName" />
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkSel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="cmdMoveRight" runat="server" Text="Move->" style="float:right" CssClass="btn" OnClick="cmdMoveRight_Click" />
</div>
<div style="float:left;width: 40%;margin-left:10px">
<asp:GridView ID="GridView2" runat="server"
AutoGenerateColumns="False" DataKeyNames="ID" cssclass="table">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" SortExpression="HotelName" />
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkSel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="cmdMoveMoveLeft" runat="server" Text="<-Move" CssClass="btn" OnClick="cmdMoveMoveLeft_Click" />
</div>
Code to load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGrids();
}
}
void LoadGrids()
{
SqlCommand cmdSQL = new SqlCommand("SELECT * from tblHotelsA");
GridView1.DataSource = MyRstP(cmdSQL);
GridView1.DataBind();
cmdSQL.CommandText = "SELECT * from tblHotelsB";
GridView2.DataSource = MyRstP(cmdSQL);
GridView2.DataBind();
}
public DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
Ok, so now we have this:
Ok, now a button to move right, and one to move left. Code is:
protected void cmdMoveRight_Click(object sender, EventArgs e)
{
// move records right A to table B
string strSQL =
"INSERT INTO tblHotelsB (FirstName, LastName, HotelName, Description) " +
"SELECT FirstName, LastName, HotelName, Description FROM tblHotelsA " +
"WHERE tblHotelsA.id = #ID";
string strSQLDel = "DELETE FROM tblHotelsA WHERE ID = #ID";
MoveRows(GridView1,strSQL,strSQLDel);
}
protected void cmdMoveMoveLeft_Click(object sender, EventArgs e)
{
// move records right A to table B
string strSQL =
"INSERT INTO tblHotelsA (FirstName, LastName, HotelName, Description) " +
"SELECT FirstName, LastName, HotelName, Description FROM tblHotelsB " +
"WHERE tblHotelsB.id = #ID";
string strSQLDel = "DELETE FROM tblHotelsB WHERE ID = #ID";
MoveRows(GridView2, strSQL,strSQLDel);
}
void MoveRows(GridView gv,string strSQL, string strSQLDel)
{
foreach (GridViewRow OneRow in gv.Rows)
{
CheckBox ckBox = OneRow.FindControl("cHkSel") as CheckBox;
if (ckBox.Checked)
{
int PKID = (int)gv.DataKeys[OneRow.RowIndex]["ID"];
SqlCommand cmdSQL = new SqlCommand(strSQL);
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PKID;
SqlRun(cmdSQL);
// delte the row
cmdSQL.CommandText = strSQLDel;
SqlRun(cmdSQL);
}
}
// now re-load both grids to reflect changes
LoadGrids();
}
public void SqlRun(SqlCommand cmdSQL)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
cmdSQL.ExecuteNonQuery();
}
}
}
I have a reservation system and I am having a problem with my delete link that is inside my gridview that is supposedly to delete temporarily reserved rooms, it returns an error page stating that "Deleting is not supported by data source 'SqlDataSource1' unless DeleteCommand is specified." but when I relog-in the account I used the data was removed. Here is my code
ASP.net
<asp:GridView ID="cartGView" runat="server" DataKeyNames="ROOM_ID" AutoGenerateColumns="False" BackColor="White" BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4" Width="100%" DataSourceID="SqlDataSource1" GridLines="Horizontal" OnRowDeleting="cartGView_RowDeleting">
<RowStyle HorizontalAlign ="Center" />
<Columns>
<asp:CommandField SelectText="Delete" ShowDeleteButton="True" />
<asp:BoundField DataField="ROOM_ID" HeaderText="Room ID" SortExpression="ROOM_ID" HeaderStyle-HorizontalAlign="Center">
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
</asp:BoundField>
<asp:BoundField DataField="ROOM_TYPE" HeaderText="Room Type" SortExpression="ROOM_TYPE" HeaderStyle-HorizontalAlign="Center">
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
</asp:BoundField>
<asp:BoundField DataField="NO_GUEST" HeaderText="Guest" SortExpression="NO_GUEST" HeaderStyle-HorizontalAlign="Center">
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
</asp:BoundField>
<asp:BoundField DataField="PRICE" HeaderText="Price" SortExpression="PRICE" HeaderStyle-HorizontalAlign="Center">
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
</asp:BoundField>
<asp:BoundField DataField="SUB_PRICE" HeaderText="Sub Price" SortExpression="SUB_PRICE" HeaderStyle-HorizontalAlign="Center">
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
</asp:BoundField>
</Columns>
<EmptyDataTemplate>
<br></br><center>Select Room</center>
<br></br>
</EmptyDataTemplate>
<FooterStyle BackColor="White" ForeColor="#333333" />
<HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#487575" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#275353" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Bakasyunan %>" SelectCommand="SELECT DISTINCT [ROOM_ID], [ROOM_TYPE], [PRICE], [SUB_PRICE], [NO_GUEST] FROM [TBL_MyCart] WHERE ([USERNAME] = #USERNAME)" OnSelecting="SqlDataSource1_Selecting">
<SelectParameters>
<asp:SessionParameter Name="USERNAME" SessionField="username" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
C#:
protected void cartGView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
string roomid = Convert.ToString(cartGView.DataKeys[e.RowIndex].Values[0]);
cd.DeleteRecordWalkCart(roomid);
cartGView.DataSourceID = "SqlDataSource1";
cartGView.DataBind();
if (cartGView.Rows.Count == 0)
{
subtotalBox.Text = "P 0.00";
continueBtn.Enabled = false;
continueBtn.BackColor = System.Drawing.ColorTranslator.FromHtml("#2C2A2A");
}
else if (cartGView.Rows.Count > 0)
{
SqlCommand sumcmd = new SqlCommand("SELECT SUM(SUB_PRICE) FROM TBL_MyCart", conn); //<-- Add Subtotal
conn.Open();
string sum = sumcmd.ExecuteScalar().ToString();
conn.Close();
subtotalBox.Text = "P " + sum + ".00";
continueBtn.Enabled = true;
continueBtn.BackColor = System.Drawing.ColorTranslator.FromHtml("#6c0404");
}
}
catch(Exception ex)
{
Label1.Text = ex.Message;
}
}
Any help will be much appreciated! Thank you!
I'm implementing an "edit" feature on my Gridview bound to my "books" table. I'm receiving an error on RowEditingEvent wasn't handled. I don't understand where I'm going wrong or if I'm missing a reference somewhere but it seems to me that everything is handled.
public partial class AddEdit_Text_Books : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
string query = "select * from textBooks ";
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["HUTDMSConnectionString"].ToString()))
using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
adapter.Fill(dt);
ViewState["allBooks"] = dt;
this.BindGrid();
}
}
protected void BindGrid()
{
GridView1.DataSource = ViewState["allBooks"] as DataTable;
GridView1.DataBind();
}
protected void OnRowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
this.BindGrid();
}
protected void OnUpdate(object sender, EventArgs e)
{
GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow;
string name = (row.Cells[0].Controls[0] as TextBox).Text;
string country = (row.Cells[1].Controls[0] as TextBox).Text;
DataTable dt = ViewState["allBooks"] as DataTable;
ViewState["allBooks"] = dt;
GridView1.EditIndex = -1;
this.BindGrid();
}
protected void OnCancel(object sender, EventArgs e)
{
GridView1.EditIndex = -1;
this.BindGrid();
}
}
}
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="BookID" Width="1482px" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="thirteenISBN" HeaderText="thirteenISBN" SortExpression="thirteenISBN" />
<asp:BoundField DataField="CourseID" HeaderText="CourseID" SortExpression="CourseID" />
<asp:BoundField DataField="BookTitle" HeaderText="BookTitle" SortExpression="BookTitle" />
<asp:BoundField DataField="Ancillary" HeaderText="Ancillary" SortExpression="Ancillary" />
<asp:BoundField DataField="BookActive" HeaderText="BookActive" SortExpression="BookActive" />
<asp:BoundField DataField="ActiveDate" HeaderText="ActiveDate" SortExpression="ActiveDate" />
<asp:BoundField DataField="InactiveDate" HeaderText="InactiveDate" SortExpression="InactiveDate" />
<asp:BoundField DataField="Author" HeaderText="Author" SortExpression="Author" />
<asp:BoundField DataField="BookID" HeaderText="BookID" InsertVisible="False" ReadOnly="True" SortExpression="BookID" />
<asp:BoundField DataField="Notes" HeaderText="Notes" SortExpression="Notes" />
<asp:BoundField DataField="eISBN" HeaderText="eISBN" SortExpression="eISBN" />
<asp:BoundField DataField="ebookAvailable" HeaderText="ebookAvailable" SortExpression="ebookAvailable" />
<asp:BoundField DataField="VendorISBN" HeaderText="VendorISBN" SortExpression="VendorISBN" />
<asp:BoundField DataField="tenISBN" HeaderText="tenISBN" SortExpression="tenISBN" />
<asp:BoundField DataField="EditionAndDate" HeaderText="EditionAndDate" SortExpression="EditionAndDate" />
<asp:BoundField DataField="Publisher" HeaderText="Publisher" SortExpression="Publisher" />
<asp:BoundField DataField="Imprint" HeaderText="Imprint" SortExpression="Imprint" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Edit" runat="server" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton Text="Update" runat="server" OnClick="OnUpdate" />
<asp:LinkButton Text="Cancel" runat="server" OnClick="OnCancel" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:HUTDMSConnectionString %>" SelectCommand="SELECT [thirteenISBN], [CourseID], [BookTitle], [Ancillary], [BookActive], [ActiveDate], [InactiveDate], [Author], [BookID], [Notes], [eISBN], [ebookAvailable], [VendorISBN], [tenISBN], [EditionAndDate], [Publisher], [Imprint] FROM [textBooks]"></asp:SqlDataSource>
You have not registered onediting event in gridview definition.
Add OnRowEditing ="OnRowEditing" in below gridview definition.
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AutoGenerateColumns="False" DataKeyNames="BookID" Width="1482px"
CellPadding="4" ForeColor="#333333" GridLines="None" OnRowEditing ="OnRowEditing">
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.