GridView doesn't show - c#

Working on a basic C# web app here and I can't seem to get the GridView to show. I can see that its passing the code through because it changes my image from one to another but for some reason the Gridview doesn't show up. Using the button for the postback and my dropdown box has the variable for my stored procedure. I'm new to C# web apps (Vb Win app guy here) so I need a little guidance please.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, System.EventArgs e)
{
//This is where my postback begins...
if (IsPostBack)
{
string Quote = null;
System.Data.SqlClient.SqlConnection myDatabaseConnection = null;
System.Data.SqlClient.SqlCommand myCommand = null;
System.Data.SqlClient.SqlDataReader myReader = null;
// Validate the SP
Page.Validate();
if (Page.IsValid)
{
Quote = DropDownList1.Text.ToString();
try
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Data1"].ConnectionString;
myDatabaseConnection = new System.Data.SqlClient.SqlConnection(connectionString);
myCommand = new System.Data.SqlClient.SqlCommand();
//Set up to use my stored procedure:
myCommand.CommandType = System.Data.CommandType.StoredProcedure;
myCommand.Connection = myDatabaseConnection;
myCommand.CommandText = "EditDataPage";
myCommand.Parameters.AddWithValue("#QuoteNumber", Quote);
//Use an SqlDataReader to execute the stored procedure and
//get the results into the GridView:
myDatabaseConnection.Open();
myReader = myCommand.ExecuteReader();
GridView1.DataSource = myReader;
GridView1.DataBind();
myDatabaseConnection.Close();
myDatabaseConnection.Dispose();
GridView1.Visible = true;
Image1.Visible = false;
Image2.Visible = true;
}
catch (System.Data.SqlClient.SqlException exception)
{
ErrorLabel.Visible = true;
}
catch (Exception exception)
{
ErrorLabel.Visible = true;
//Do cleanup tasks here:
}
finally
{
myCommand = null;
if ((myReader != null) && !myReader.IsClosed)
{
myReader.Close();
}
myReader = null;
if ((myDatabaseConnection != null) && myDatabaseConnection.State == System.Data.ConnectionState.Open)
{
myDatabaseConnection.Close();
myDatabaseConnection.Dispose();
}
myDatabaseConnection = null;
}
}
}
}
}
Heres my aspx code:
Edit Data
Use the controls to move within the dataset, then edit and save what you need
for your reports.
<table class="yui-d0f">
</table>
<table class="yui-main">
<tr>
<td>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:Data1 %>"
SelectCommand="EditDataPage" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:FormParameter FormField="DropDownList1" Name="QuoteNumber" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<table class="style1">
<tr>
<td align="center">
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="DropDownList"
DataTextField="QuoteNumber" DataValueField="QuoteNumber" Height="23px"
Width="188px">
</asp:DropDownList>
<asp:SqlDataSource ID="DropDownList" runat="server"
ConnectionString="<%$ ConnectionStrings:Data1 %>"
SelectCommand="SELECT QuoteNumber FROM SF1411 GROUP BY QuoteNumber">
</asp:SqlDataSource>
</td>
<td>
<table class="style1">
<tr>
<td class="style2">
<asp:Button ID="ListAllButton" runat="server" Height="32px" Text="Show Data"
Width="111px" PostBackUrl="~/EditData.aspx" />
</td>
<td>
<asp:Image ID="Image1" runat="server"
ImageUrl="~/_assets/img/lock-disabled-icon.png" />
<asp:Image ID="Image2" runat="server" ImageUrl="~/_assets/img/lock-icon.png"
Visible="False" />
</td>
</tr>
</table>
</td>
</tr>
</table>
<asp:Label ID="ErrorLabel" runat="server" Font-Underline="True"
ForeColor="Maroon" Text="Error in Processing, try again later." Visible="False"></asp:Label>
</td>
</tr>
</table>
<asp:GridView ID="GridView1" runat="server" CssClass="styled"
AutoGenerateColumns="False">
</asp:GridView>

I'm not 100% sure, but the fact that you've got AutoGenerateColumns="false" on your GridView yet no columns defined looks a bit suspicious. I guess as a quick test you could change this attribute to true and see what happens.
If you do indeed want to specify the columns yourself (which in my experience is the norm), then you need to specify them, like this for example:
<asp:GridView ...>
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:TemplateField>
<asp:Label Text='<%# Eval("Surname") %>' runat="server" />
</asp:TemplateField>
</Columns>
</asp:GridView>
See MSDN for more details.

Related

Both DataSource and DataSourceID are defined on 'DataList1'. Remove one definition

Heres the dropdownlist and datalist code
<div>
Sort by Category:
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>All</asp:ListItem>
<asp:ListItem>Decoration</asp:ListItem>
<asp:ListItem>Catering</asp:ListItem>
<asp:ListItem>Entertainment</asp:ListItem>
<asp:ListItem>Sound</asp:ListItem>
<asp:ListItem>Others</asp:ListItem>
</asp:DropDownList>
<asp:DataList ID="DataList1" runat="server"
GridLines="Both" RepeatColumns="4" RepeatDirection="Horizontal"
Width="1000px" DataSourceID="SqlDataSource1" >
<ItemTemplate>
<table class="nav-justified">
<tr>
<td class="text-center">
<strong>
<asp:Label ID="Label1" runat="server"
Text='<%# Eval("serName") %>'></asp:Label>
</strong>
</td>
</tr>
<tr>
<td>
<asp:Image ID="Image1" runat="server" Height="179px"
ImageUrl='<%# Eval("serImg") %>' Width="191px"/>
</td>
</tr>
<tr>
<td>
<strong>
<asp:Label ID="Label2" runat="server" Text="Rs"></asp:Label>
<asp:Label ID="Label3" runat="server"
Text='<%# Eval("sprice") %>'>
</asp:Label>
</strong>
</td>
</tr>
<tr>
<td class="text-center">
<asp:Button ID="Button1" runat="server" Text="Details" />
</td>
</tr>
</table>
<br />
</ItemTemplate>
</asp:DataList>
</div>
Here is the .cs code. Its purpose is to filter the data in the list according to the selected category in the dropdown list
protected void Page_Load(object sender, EventArgs e)
{
String conString = ConfigurationManager.ConnectionStrings["regcon"].ConnectionString;
string query = "select * from addService where serCategory=#cat";
SqlCommand cmd = new SqlCommand(query);
cmd.Parameters.AddWithValue("#cat", DropDownList1.SelectedItem.Value);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
DataList1.DataSource = ds;
DataList1.DataBind();
}
}
}
}
I get the error "Both DataSource and DataSourceID are defined on 'DataList1'. Remove one definition." when i run it.Removing the Datalist1 or DataSourceID would give an error.How do i fix this?
The problem is, on the datalist you have a datasource
DataSourceID="SqlDataSource1"
Then you also apply a data source in the code behind
DataList1.DataSource = ds;
You can't do both. You could remove the existing one in code then apply a new one if you want.

How to insert records from textboxes and checkboxes into a gridview on button click?

I am trying to insert records from textboxes and checkboxes on an imagebutton click to a gridview. On every click, I want the records to be inserted into gridview and the old records added should remain unless I remove it from gridview. Help would be appreciated. Here is my codes in the GUI. Thanks!
<tr>
<td align="center" class="tblborder">
<strong>Team Member(s)</strong>
</td>
<td align="center" style="width:23%" class="tblborder">
<asp:TextBox ID="txtCTName" runat="server" Width="80%"></asp:TextBox>
<asp:imagebutton ID="btnCTName" name="btnChangeTeam" class="buttonsearch" runat="server" Height="16px" ImageUrl="~/Images/search.jpg" Width="16px" />
</td>
<td align="center" style="width:27%" class="tblborder">
<asp:TextBox ID="txtCTPosition" runat="server" Width="100%"></asp:TextBox>
</td>
<td align="center" style="width:10%" class="tblborder">
<asp:CheckBox ID="chkCTSignOff" Runat="server"/>
</td>
<td align="center" style="width:20%" class="tblborder">
<asp:Label ID="lblCTDate" runat="server"></asp:Label>
</td>
<td align="center" style="width:8%" class="tblborder">
<asp:ImageButton ID="imgAddCT" runat="server" ImageUrl="~/Images/addsign.png"
Height="20px" Width="20px" onclick="imgAddCT_Click" />
</td>
</tr>
<tr>
<td colspan="6">
<asp:GridView ID="gvChangeTeam" runat="server" Width="100%" AutoGenerateColumns="False" Visible="False">
<Columns>
<asp:BoundField HeaderText="Name" DataField="TeamName" ItemStyle-Width="30%" />
<asp:BoundField HeaderText="Position" DataField="TeamPosition" ItemStyle-Width="20%"/>
<asp:BoundField HeaderText="Sign Off" DataField="TeamSignature" ItemStyle-Width="10%"/>
<asp:BoundField HeaderText="Date" DataField="TeamDate" ItemStyle-Width="20%"/>
<asp:buttonfield ButtonType="Image" ImageUrl="../Images/deletesign.png" commandname="ibtnDelete" HeaderText="Delete" ItemStyle-Width="5%" ControlStyle-Height="20" />
</Columns>
</asp:GridView>
</td>
</tr>
You cannot retrieve data source of controls (GridView in this case) on postback. So options are to use view state, session etc. basically to persist original data during postbacks. These are also called as ASP.NET State Management techniques.
I purposely avoided using ViewState here because if your original dataset or datatable is huge it would kill the page. Even with Session there's a problem because it would get cleared after default session timeout value or whatever value you have set in config.
Although each one of these techniques has limitations, I am just going ahead to show you how it could be done with Session.
ASPX
<form id="form1" runat="server">
<div>
<label>Username</label>
<asp:TextBox runat="server" ID="txt1" />
<asp:Button Text="Add" runat="server" OnClick="AddUsername" />
<asp:GridView runat="server" ID="gv1">
<Columns>
<asp:BoundField DataField="Username" HeaderText="Username" />
</Columns>
</asp:GridView>
</div>
</form>
Code-behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var dt = GetInitialData();
gv1.DataSource = dt;
gv1.DataBind();
Session["dt"] = dt;
}
}
protected void AddUsername(object sender, EventArgs e)
{
var dt = Session["dt"] as DataTable;
var row = dt.NewRow();
row["Username"] = txt1.Text;
dt.Rows.Add(row);
gv1.DataSource = dt;
gv1.DataBind();
Session["dt"] = dt;
}
private DataTable GetInitialData()
{
var dt = new DataTable();
dt.Columns.Add("Username");
for (int i = 1; i <= 5; i++)
{
var row = dt.NewRow();
row["Username"] = string.Format("user name {0}", i);
dt.Rows.Add(row);
}
return dt;
}

How to get each row data using button field in gridview to display in textbox?

I want to display my gridview details in respective textbox by clicking Edit buttonfield appear in gridview. I am able get only first row(row[0]) data, either by default or by clicking all over the another rows. But I need each row by clicking each row edit button. Here is my design code. I am using VS 2013 and SQL Server 2012.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Admin.aspx.cs" Inherits="RigoTest.Admin" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
width: 50%;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<center>
<asp:GridView ID="gvdetails" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333"
GridLines="None" Width="800px" HorizontalAlign="Center" OnRowEditing="gvdetails_RowEditing" OnRowCommand="gvdetails_RowCommand">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<%--<asp:TemplateField HeaderText="ID" Visible="false">
<EditItemTemplate>
<asp:TextBox ID="txtID" runat="server" Text='<%# Bind("ID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Question">
<EditItemTemplate>
<asp:TextBox ID="txtQue" runat="server" Text='<%# Bind("question") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblQue" runat="server" Text='<%# Bind("question") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
--%>
<asp:BoundField DataField="ID" HeaderText="ID" Visible="false" />
<asp:BoundField DataField="question" HeaderText="Question" />
<%--<asp:CommandField ShowEditButton="True" HeaderText="Edit2" />--%>
<asp:ButtonField HeaderText="Edit" CommandName="edit" Text="Edit" />
<%--<asp:CommandField CausesValidation="False" HeaderText="Edit2" InsertVisible="False" ShowCancelButton="False" ShowEditButton="True" UpdateText="" />--%>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" />
<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>
</center>
</div>
<div style="height: 300px; margin-top: 250px">
<center>
<table width="40%" class="auto-style1">
<tr>
<td>
Add/Edit Question</td>
<td>
</td>
<td> </td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td> </td>
</tr>
<tr>
<td>
<asp:Label ID="Label5" runat="server" Text="Question :"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtquestion" runat="server" Width="295px"></asp:TextBox>
</td>
<td> </td>
</tr>
<tr>
<td>
<asp:Label ID="Label3" runat="server" Text="Option :"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtoption" runat="server" Width="295px"></asp:TextBox>
</td>
<td>
<asp:Button ID="btnadd" runat="server" Text="Add" Width="50px" OnClick="btnadd_Click" />
</td>
</tr>
<tr>
<td> </td>
<td>
<asp:ListBox ID="ListBox1" runat="server" Width="300px"></asp:ListBox>
</td>
<td>
<asp:Button ID="btndelete" runat="server" Text="Delete" Width="50px" OnClick="btndelete_Click" />
<br />
<br />
<asp:Button ID="btnselect" runat="server" Text="Select" Width="50px" OnClick="btnselect_Click" />
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label4" runat="server" Text="Correct Option :"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtcorrectoption" runat="server" Width="295px"></asp:TextBox>
</td>
<td> </td>
</tr>
<tr>
<td>
<br />
<asp:Button ID="btnsave" runat="server" Text="Save" Width="100px" />
</td>
<td> </td>
<td> </td>
</tr>
</table>
</center>
</div>
</form>
</body>
HERE IS MY ASP.NET CODE
public partial class Admin : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("server = yamma; uid = sa; pwd = /*-; database = rigo");
SqlCommand cmd;
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
public static DataTable dtDefault = new DataTable();
public Int64 n;
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
showdata();
//string EditID = Request.QueryString["EditId"];
}
}
public void showdata()
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
cmd = new SqlCommand("RigoSelect", con);
cmd.CommandType = CommandType.StoredProcedure;
da.SelectCommand = cmd;
da.Fill(dt);
da.Fill(dtDefault);
gvdetails.DataSource = dt;
gvdetails.DataBind();
}
protected void btnadd_Click(object sender, EventArgs e)
{
ListBox1.Items.Add(txtoption.Text); //to select data from textbox to listbox
}
protected void btndelete_Click(object sender, EventArgs e)
{
string remove = ListBox1.SelectedItem.Text;
ListBox1.Items.Remove(remove);
////clear all items in listbox
//listBox1.Items.Clear();
}
protected void btnselect_Click(object sender, EventArgs e)
{
txtcorrectoption.Text = ListBox1.SelectedItem.Text;
}
protected void gvdetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
//private Int64 n;
//for(int i=0;i<=n;i++)
//{
int id = int.Parse(gvdetails.Rows[0].Cells[0].Text);
DataRow[] dr = null;
dr = dtDefault.Select("ID = '" + id + "'");
txtquestion.Text = dr[0]["question"].ToString();
txtoption.Text = dr[0]["options"].ToString();
//}
showdata();
}
protected void gvdetails_RowEditing(object sender, GridViewEditEventArgs e)
{
// when boundfied is exist in gridview then id can get....thisway
//int id = int.Parse(gvdetails.Rows[e.NewEditIndex].Cells[0].Text);
////Label lbl = (Label)gvdetails.Rows[e.NewEditIndex].Cells[0].FindControl("lblID");
////string id = lbl.Text.Trim();
////int EID = int.Parse(id);
//// Response.Redirect("Admin.aspx?EditId=" + id + "");
//DataRow[] dr = null;
//dr = dtDefault.Select("ID = '" + id + "'");
//txtquestion.Text = dr[0]["question"].ToString();
//txtoption.Text = dr[0]["options"].ToString();
//showdata();
}
}
}
My problem occurs here
protected void gvdetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
//private Int64 n;
//for(int i=0;i<=n;i++)
//{
int id = int.Parse(gvdetails.Rows[0].Cells[0].Text);
DataRow[] dr = null;
dr = dtDefault.Select("ID = '" + id + "'");
txtquestion.Text = dr[0]["question"].ToString();
txtoption.Text = dr[0]["options"].ToString();
//}
showdata();
}
Here is my main problem occurs:
protected void gvdetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
//private Int64 n;
//for(int i=0;i<=n;i++)
//{
int id = int.Parse(gvdetails.Rows[0].Cells[0].Text);
DataRow[] dr = null;
dr = dtDefault.Select("ID = '" + id + "'");
txtquestion.Text = dr[0]["question"].ToString();
txtoption.Text = dr[0]["options"].ToString();
//}
showdata();
}
When I click on any row that display only first row data. I want to get each row data by each clicking on respective textbox of grid row.
I have tried with commandfield but when try to add the data of option textbox (txtoption) in listbox with add button, it automatically display update, cancel option in gridview.
In the gvdetails_RowCommand event, you're always accessing the first row in the GridView.
int id = int.Parse(gvdetails.Rows[0].Cells[0].Text);
See if this works instead (referencing the currently selected row):
int id = int.Parse(gvdetails.SelectedRow.Cells[0].Text);
Here is a sample code for your reference. Hope this helps.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName =="edit")
{
int i = Convert.ToInt32(e.CommandArgument);
YourTextBox1.Text = GridView1.Rows[i].Cells[0].Text;
YourTextBox2.Text = GridView1.Rows[i].Cells[1].Text;
}
}

Change 1 as Enabled and 0 as disabled while binding the grid for a column

I am having a grid and below is the code which I had written for it. In my grid for this column i.e. <asp:BoundField DataField = "IsNOWEnabled" HeaderText = "Enabled/Disabled" HtmlEncode = "true"/> , from the database either 1 or 0 is coming. I want that while the binding the grid replace the text 1 by enabled and 0 by disabled for this column so that when the grid binds it display 1 as enabled and 0 as disabled for column Enabled/Disabled.
Please guide me , how i achieve this.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" Width = "550px" AutoGenerateColumns = "false" AlternatingRowStyle-BackColor = "#C2D69B" HeaderStyle-BackColor = "green" AllowPaging ="true" OnPageIndexChanging = "OnPaging" PageSize = "10" >
<Columns>
<asp:BoundField DataField = "NatureOfWorkID" HeaderText = "Nature Of WorkID" HtmlEncode = "true" Visible="false" />
<asp:BoundField DataField = "NatureOFWorkName" HeaderText = "Nature Of Work Name" HtmlEncode = "true" />
<asp:BoundField DataField = "IsNOWEnabled" HeaderText = "Enabled/Disabled" HtmlEncode = "true"/>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "NatureOfWorkID">
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" Text = "Edit" OnClick = "Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="#C2D69B" />
</asp:GridView>
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick = "Add" />
<asp:Panel ID="pnlAddEdit" runat="server" CssClass="modalPopup" style = "display:none">
<asp:Label Font-Bold = "true" ID = "Label4" runat = "server" Text = "Nature Of Work Details" ></asp:Label>
<br />
<table align = "center">
<tr>
<td>
<asp:Label ID = "Label2" runat = "server" Text = "Nature Of Work Name" ></asp:Label>
</td>
<td>
<asp:TextBox ID="txtNOWname" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:RadioButton id="RBEnable" Text="Enabled" runat="server"/>
<br>
<asp:RadioButton id="RBDisable" Text="Disabled" runat="server"/>
<br>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick = "Save" />
</td>
<td>
<asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClientClick = "return Hidepopup()"/>
</td>
</tr>
</table>
</asp:Panel>
<asp:LinkButton ID="lnkFake" runat="server"></asp:LinkButton>
<cc1:ModalPopupExtender ID="popup" runat="server" DropShadow="false"
PopupControlID="pnlAddEdit" TargetControlID = "lnkFake"
BackgroundCssClass="modalBackground">
</cc1:ModalPopupExtender>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID = "GridView1" />
<asp:AsyncPostBackTrigger ControlID = "btnSave" />
</Triggers>
The code behind is :-
private String strConnString = ConfigurationManager.ConnectionStrings["TempConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
}
}
private void BindData()
{
string strQuery = "select NatureOfWorkID,NatureOfWorkName,IsNOWEnabled" +
" from NatureOfWork";
SqlCommand cmd = new SqlCommand(strQuery);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
}
}
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
this.BindData();
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
If your B logic increases then declare a public method and use it similar to inline if
example
Code Behind
public string IsNowEnable(object data)
{
return (int)data == 1 ? "Enabled" : "Disabled";
}
and then in aspx
<asp:Label Text="<%# IsNowEnable(Eval("IsNOWEnabled"))%>" runat="server" />
Use RowDatabound Event and DataRowView Property as follow...
void GridView_RowDataBound (Object sender, GridViewRowEventArgs e)
{
// Check for a row in edit mode.
if(e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView rowView = (DataRowView)e.Row.DataItem;
e.Row.Cells[2].Text=rowView["IsNOWEnabled"].ToString()=="1"?"Enabled":"Disabled";
}
}
Why don't you use asp.net label instead of bounded fields? and then you can change the text of asp.net label in ItemDataBound event of GridView.
Just use markup. You could use another TemplateField for this one. Something like:
<asp:TemplateField HeaderText="Enabled/Disabled" SortExpression="IsNOWEnabled">
<ItemTemplate>
<%# ((bool)Eval("IsNOWEnabled"))? "Enabled" : "Disabled" %>
</ItemTemplate>
</asp:TemplateField>
You could use an inline if statement like:
<asp:Label Text="<%# Eval("IsNOWEnabled") == 1 ? "Enabled" : "Disabled" %>" runat="server" />

How to get this DataList with the paging property?

I am a new ASP.NET developer and I am developing a web-based application in which I have a DataList and I need to have a paging feature. I followed what is explained in this post in the CodeProject, but it did not work with me and I got this error which I could not be able to understand it.
Error:
The name 'CurrentPage' does not exist in the current context.
So how to fix this error and get the Paging feature in this DataList?
ASP.NET code:
<tr>
<td width="100%">
<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource2" >
<ItemTemplate>
<asp:HyperLink
ID="HyperLink1" runat="server" NavigateUrl='<%# "StartQuiz.aspx?testid=" + Eval("QuizID") %>'
Text='<%# Eval("Title") %>'></asp:HyperLink><br />
<asp:Label
ID="DescriptionLabel" runat="server" CssClass="generaltext" Text='<%# Eval("Description") %>'></asp:Label> <br />
<br />
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
SelectCommand="SELECT [Title], [Description], [QuizID],[IsSent] FROM [Quiz] where [IsSent]=1 order by [QuizID] DESC">
</asp:SqlDataSource>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblCurrentPage" runat="server" Visible="true"></asp:Label>
</td>
</tr>
<tr>
<td align="center">
<asp:Button ID="cmdPrev" runat="server" Text=" << " OnClick="cmdPrev_Click" />
<asp:Button ID="cmdNext" runat="server" Text=" >> " OnClick="cmdNext_Click" />
</td>
</tr>
Code-Behind:
protected void items()
{
PagedDataSource objDs = new PagedDataSource();
DataView dv = (DataView)SqlDataSource2.Select(DataSourceSelectArguments.Empty);
objDs.DataSource = dv;
objDs.AllowPaging = true;
objDs.PageSize = 5;
objDs.CurrentPageIndex = CurrentPage;
lblCurrentPage.Text = "Page:" + (CurrentPage + 1).ToString() + " Of " + objDs.PageCount.ToString();
cmdPrev.Enabled = !objDs.IsFirstPage;
cmdNext.Enabled = !objDs.IsLastPage;
DataList1.DataSource = objDs;
DataList1.DataBind();
}
protected void cmdPrev_Click(object sender, EventArgs e)
{
try
{
CurrentPage -= 1;
items();
}
catch (Exception ex)
{
Logger.LogException(ex);
}
}
protected void cmdNext_Click(object sender, EventArgs e)
{
try
{
CurrentPage += 1;
items();
}
catch (Exception ex)
{
Logger.LogException(ex);
}
}
Declare "CurrentPage variable at the Top of everything" i believe in your case it should be int CurrentPage = 1;

Categories