Displaying Data in GridView using Dataset - data-binding

I am trying to display a dataset to my ASP.NET application. It seems that when I click the button event, the data is not displaying in the grid.
I have a basic page with the following:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel runat="server" id="UpdatePanel" updatemode="Conditional">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" Width="200" Height="300">
</asp:GridView>
<asp:Button runat="server" id="UpdateButton1" onclick="UpdateButton_Click" text="Update" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
Then in the code behind, I have the following:
protected void UpdateButton_Click(object sender, EventArgs e)
{
string SQLConfigSettings = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(SQLConfigSettings);
sqlconn.Open();
SqlDataAdapter adapter = new SqlDataAdapter("Select * from Student", sqlconn);
DataSet ds = new DataSet();
adapter.Fill(ds);
GridView1.DataSource = ds;
UpdatePanel.Update();
}
Am I missing something? Shoudlnt the dataset be diaplayed in the grid?
When I click the button nothing happens.
Thanks :)

You need to add
GridView1.DataBind() right after Gridview1.DataSource.
So it becomes:
...
DataSet ds = new DataSet();
adapter.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
UpdatePanel.Update();
If you need more information about the .DataBind method check MSDN on it

GridView1.DataSource = ds;
Try to mention table inside dataset. Something like ds.Tables[0] or if you know name of table ds.Tables["table_name"]

Put a breakpoint on the first line of code in UpdateButton_Click and run it.
Is that breakpoint reached?
Step through each line of code after that and examine the variable values. Is the DataSet being filled? Can you see the DataTable and its DataRows?
If you reach this event code and have data, then you need to look at the databinding. You need to do GridView.DataBind() immediately after setting the DataSource and before doing the UpdatePanel.Update(). Then you should be good to go.

Related

Putting data from SQL query into grid view asp.net

I have a grid box in which I want to fill data from a database where the username is one and their location was added in the last 24 hours.
I have tested the SQL query and it is working fine, however when trying to put the data in a grid box nothing happens.
Here is the code I have used in the aspx.cs file:
public partial class last24hours : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(#"Data Source = sql2008.net.dcs.hull.ac.uk; Initial Catalog = rde_514872; Integrated Security = True");
protected void Page_Load(object sender, EventArgs e)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT Location FROM StaffLocation WHERE [Date and Time]>= getdate()-1 AND [Username] = '1'";
cmd.Connection = con;
DataTable dt = new DataTable();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
gridView1 is an empty grid view I have made with no sql source.
This is how the gridview is initialised in the aspx file:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
</asp:GridView>
You have AutoGenerateColumns set to false. And since you haven't defined any columns manually, of course nothing is going to show up. There's two fixes:
Set auto generate columns to true.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" />
Or manually define your columns
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Location" HeaderText="Location" SortExpression="Location" />
</Columns>
</asp:GridView>

How to Redirect to new asp page while clicking on the data row of the data grid view in asp.net

My data grid view in asp.net displays only selected id from sql server database as a single row.
Now I need to display a particular page when I click on the particular id (data row) and also I want to display all the details in a new page belongs to the selected id (on click on the id).
I have tried this code:
protected void btnserch_Click(object sender, EventArgs e)
{
SqlConnection objsqlconnection = new SqlConnection(CONNECTIONSTRING);
string query = "Select id from registration";
SqlCommand objsqlcommand = new SqlCommand(query, objsqlconnection);
objsqlconnection.Open();
SqlDataAdapter da=new SqlDataAdapter();
DataSet ds=new DataSet();
objsqlcommand.CommandText = query;
objsqlcommand.Connection = objsqlconnection;
da = new SqlDataAdapter(objsqlcommand);
da.Fill(ds);
objsqlcommand.ExecuteNonQuery();
GridView1.DataSource = ds;
GridView1.DataBind();
objsqlconnection.Close();
}
This code returns a grid by selecting only id column from registration table. Now when I click on the data row of the id column, I need an another page which should display all the details belonging to that id.
like #MelanciaUK said "OnItemDataBound" is your friend.
For checking ID even on postback, select it in "SelectedIndexChanging"
hope it helps.
Easiest way to redirect to new page:
<asp:GridView ID="grd" runat="server" autogeneratedcolumn="false">
<asp:TemplateField HaderText="ID">
<ItemTemplate>
<%#Eval("ID")%>
<ItemTemplate>
<asp:TemplateField>
<asp:TemplateField HaderText="Name">
<ItemTemplate>
<%#Eval("ID")%>
<ItemTemplate>
<asp:TemplateField>
<asp:TemplateField HaderText="Edit">
<ItemTemplate>
<a href='Newpage.aspx?ID=<%#Eval("ID")%>'>Edit</a>
<ItemTemplate>
<asp:TemplateField>
<asp:GridView>
You can redirect from one page another page in two ways
<asp:GridView ID="grd" runat="server" autogeneratedcolumn="false">
<asp:TemplateField HaderText="Action">
<ItemTemplate>
<a href='mypage.aspx?ID=<%#Eval("RowID")%>'>Edit</a>
Edit
<ItemTemplate>
<asp:TemplateField>
<asp:GridView>
<script type="text/javascript">
function Redirect(id) {
window.location = 'mypage.aspx?ID=' + id;
}
</script>

asp.net ListView Sorting using DataBind

Sort listview using column headings in the LayoutTemplate
I am able to sort a basic list view using asp:SqlDataSource and setting the list view property DataSourceID by pointing it to the asp:SqlDataSource ID. I am having an issue when sorting when not using the asp:SqlDataSource and just DataBinding from the code behind.
SqlDataSource Example:
<asp:ListView ID="ContactsListView" DataSourceID="ContactsDataSource" runat="server">
<LayoutTemplate>
<table width="640px" runat="server">
<tr class="header" align="center" runat="server">
<td>
<asp:LinkButton runat="server" ID="SortByFirstNameButton" CommandName="Sort" Text="First Name" CommandArgument="FirstName" />
</LayoutTemplate>
....
</asp:ListView>
<asp:SqlDataSource ID="ContactsDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:MainConnString %>"
SelectCommand="SELECT * FROM TableName">
</asp:SqlDataSource>
DataBind Example:
<asp:ListView ID="ContactsListView" DataSourceID="ContactsDataSource" runat="server">
<LayoutTemplate>
<table width="640px" runat="server">
<tr class="header" align="center" runat="server">
<td>
<asp:LinkButton runat="server" ID="SortByFirstNameButton" CommandName="Sort" Text="First Name" CommandArgument="FirstName" />
</LayoutTemplate>
....
</asp:ListView>
protected void Page_Load(object sender, EventArgs e)
{
String SQL = "SELECT * FROM Customer";
SqlDataAdapter da= new SqlDataAdapter(SQL, ConnStr);
DataSet ds = new DataSet();
da.Fill(ds);
ContactsListView.DataSource = ds.Tables[0];
ContactsListView.DataBind();
}
Both code samples populate the list view, but the second example data binding does not work for sorting. With the first example, the sorting just works with the added asp:LinkButton in the LayoutTemplate adding the CommandName="sort" and setting the CommandArugment="ColumnName", but it does not work with the second example.
Can anyone please explain why and how to get the sorting working using the code behind DataBind method?
Thanks!
I solved my issue.
I added an event to handle the sorting. The event grabs the command name (Data column) and passes it and the sorting direction into a function which will make another call to the database sort the returned results and rebind to the List View.
I had to create a view state to hold the List View Sort Direction because for some reason, the onsorting event handler kept saying that the sort direction was ascending.
Front End
<asp:ListView ID="ContactsListView" OnSorting="ContactsListView_Sorting" runat="server">
<LayoutTemplate>
<table width="640px" runat="server">
<tr class="header" align="center" runat="server">
<td>
<asp:LinkButton runat="server" ID="SortByFirstNameButton" CommandName="Sort" Text="First Name" CommandArgument="FirstName" />
</LayoutTemplate>
....
</asp:ListView>
Back End
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindContacts(string.Empty);
}
}
protected SortDirection ListViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
protected void ContactsListView_Sorting(Object sender, ListViewSortEventArgs e)
{
BindContacts(e.SortExpression + " " + ListViewSortDirection.ToString());
// Check the sort direction to set the image URL accordingly.
string imgUrl;
if (ListViewSortDirection == SortDirection.Ascending)
ListViewSortDirection = SortDirection.Descending;
else
ListViewSortDirection = SortDirection.Ascending;
}
private void BindContacts(string sortExpression)
{
sortExpression = sortExpression.Replace("Ascending", "ASC");
sortExpression = sortExpression.Replace("Descending", "DESC");
using (SqlConnection conn = new SqlConnection(_connStr))
{
conn.Open();
using (SqlDataAdapter dAd = new SqlDataAdapter("SELECT * FROM Customer", conn))
{
DataTable dTable = new DataTable();
dAd.Fill(dTable);
// Sort now
dTable.DefaultView.Sort = sortExpression;
// Bind data now
ContactsListView.DataSource = dTable;
ContactsListView.DataBind();
}
conn.Close();
}
}
I guess you could try to add a handler for ListView's Sorting event. There you are given the sorting column and the sort order in the event arguments. This could be easily usable to build a specific query and bind it to the list.
Because depending on the sort expression (which you defined in your markup) SqlDataSource will very likely do something like this (I'm not sure this is exactly what it does) for you behind the scenes:
Expression<Func<DataRow,object>> myExpression = row => row["SortExpressionYouDefinedForTheColumn"];
IEnumerable<DataRow> ex = ds.Tables[0].AsEnumerable().OrderBy(myExpression.Compile());
Or SqlDataSource may be using a DataView to sort the DataTable.
SqlDataSource can do this because by default it uses a DataSet to store the result set (or so says the documentation):
The data retrieval mode identifies how a SqlDataSource control retrieves data from the underlying database.
When the DataSourceMode property is set to the DataSet value, data is
loaded into a DataSet object and stored in memory on the server. This
enables scenarios where user interface controls, such as GridView,
offer sorting, filtering, and paging capabilities..
Since you chose to bind manually to a DataSet, you need to do the "magic" yourself; in other words, you handle the OnSort command, get the sort expression, get your data source again (however you do it, from Session or by calling the database again) and do your sort similarly to the lines shown above and rebind to your Gridview.

Problem with asp.net page results

hey guys,
recently while creating a webpage with a gridview, while binding the gridview with sql database, once when i run the site, it shows me the proper results, but when i make any changes and attempt to run the site again, it does not displays the latest changes, instead it displays the results from the previous cache, but when i clears the history, then when i refresh the page, it shows proper results.
Below is my code which i am using to bind my gridview.
SqlConnection con = new SqlConnection(#"[connection string goes here]");
public void FillGrid()
{
SqlDataAdapter adap = new SqlDataAdapter("select m.ModuleID, md.FriendlyName from Modules m inner join dbo.ModuleDefinitions md on m.ModuleDefID = md.ModuleDefID", con);
DataTable dt = new DataTable();
adap.Fill(dt);
FunGrid.DataSource = dt;
}
protected void Page_Load(object sender, EventArgs e)
{
FillGrid();
FunGrid.DataBind();
}
Below is the source of the gridview as i am using boundfields to bind gridview.
<form id="form1" runat="server">
<div>
<asp:GridView ID="FunGrid" runat="server" AllowPaging="True"
AutoGenerateColumns="False" PageSize="10">
<Columns>
<asp:BoundField DataField="ModuleId" HeaderText="Module ID" />
<asp:BoundField DataField="FriendlyName" HeaderText="Module Name" />
</Columns>
</asp:GridView>
</div>
</form>
This is the first time i have got some issues like that, Please if anyone guys have came accross such issues please revert back with the resolutions...
Thanks and Regards
Abbas Electricwala
You can disable caching for the page:
<%# OutputCache Location="None" VaryByParam="None" %>
or add this to your page response:
Response.Cache.SetCacheability(HttpCacheability.NoCache);

ASP.NET GridView Cell Editing alternative

Is it possible to edit and update a GridView cell without using
<asp:TemplateField> and/or
<%# Eval("Name") %> and/or
<%# Bind("Name") %> and/or
SqlDataSource ?
NB : I want to use only C# code in the behind and SqlConnection, SqlCommand, ExecuteXXX, etc.
NB : Plz provide me code(C# and aspx) or a web-link containing code.
Use onrowediting and onrowupdating in gridview markup...
something like this:
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" AllowPaging="true" AllowSorting="true" PageSize="5" DataKeyNames="Id"
onpageindexchanging="GridView1_PageIndexChanging"
AutoGenerateEditButton="true" AutoGenerateDeleteButton="true"
onsorting="GridView1_Sorting" onrowediting="GridView1_RowEditing">
I am not very sure about winforms, but in websites try this..
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
//your code that will edit/update.
}
In general, code with Sqlcommand and Sqlconnection will be something like:
SqlConnection con;
SqlCommand cmd;
DataSet ds;
SqlDataAdapter da;
protected DataSet FillDataSet()
{
string source = "Database=GridTest;Server=Localhost;Trusted_Connection=yes";
con = new SqlConnection(source);
cmd = new SqlCommand("proc_mygrid", con);
ds = new DataSet();
da = new SqlDataAdapter(cmd);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
return ds;
}
Hope this helps.
I still don't figure out why are you fighting against asp.net, but you can do what you want using ObjectDataSource. The ObjectDataSource control uses reflection to call methods of a business object to select, update, insert, and delete data. You set the ObjectDataSource control's TypeName property to specify the name of the class to use as a source object.
Working with ObjectDataSource resume to do things like:
To Declare it:
<asp:objectdatasource
runat="server"
id="ObjectDataSource1"
typename="EmployeeLogic"
selectmethod="GetAllEmployees"
updatemethod="UpdateEmployeeInfo"
dataobjecttypename="NorthwindEmployee" />
To Create Methods into code-behind:
public List<NorthwindEmployee>GetAllEmployees()
{
//your code here
}
public void UpdateEmployeeInfo(NorthwindEmployee emp) {
//your code here
}
to Configure the GridView and to be happy :)
Below I've provided some links that might help you:
http://www.manuelabadia.com/blog/PermaLink,guid,c72852ae-1fdd-4934-a715-f565ceaf21cc.aspx
http://msdn.microsoft.com/en-us/library/57hkzhy5.aspx
http://www.google.com.br/search?hl=en-us&q=objectdatasource+asp.net
A possible solution maybe is to manage the RowDataBound event of the gridview and set the values like
e.Row.Cells(i).Text = value

Resources