I have a simple gridview, it's not displaying data - c#

My gridview source code is following
<asp:GridView ID="g1" runat="server"></asp:GridView>
and my code behind is,
bindGridView(ds.Tables[0], g1, lblErrorActivityGrid, lblActivityGridCount);
private void bindGridView(DataTable dt, GridView grd, Label lblError, Label GrdRowCount)
{
grd.DataSource = dt;
grd.DataBind();
}
my question is why my gridview is not displaying data?
I am using dataset and manually adding data in my dataset and then returning table at 0th table.
Please help. Thanks in advance

In markup set AutogenerateColumns="true" :
<asp:GridView ID="g1" AutoGenerateColumns= "true" runat="server"></asp:GridView>
Here's how I have tested your code:
In my markup I have the gridview.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="g1" AutoGenerateColumns= "true" runat="server"></asp:GridView>
<br />
<asp:Label ID="lblErrorActivityGrid" runat="server" Text="Error Activity Grid"></asp:Label>
<br />
<asp:Label ID="lblActivityGridCount" runat="server" Text="Activity Grid Count"></asp:Label>
</div>
</form>
</body>
</html>
In my code, in page load I am adding a DataTable to a DataSet and calling bindGridView method:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add("Column1", typeof(string));
dt.Columns.Add("Column2", typeof(string));
ds.Tables.Add(dt);
for (int i=0; i<5; i++)
{
DataRow nw = ds.Tables[0].NewRow();
nw[0] = (i + 1).ToString();
nw["Column1"] = (i + 1).ToString();
nw["Column2"] = String.Format("Item {0}", i);
ds.Tables[0].Rows.Add(nw);
}
bindGridView(ds.Tables[0], g1, lblErrorActivityGrid, lblActivityGridCount);
}
}
private void bindGridView(DataTable dt, GridView grd, Label lblError, Label GrdRowCount)
{
grd.DataSource = dt;
grd.DataBind();
}
And here's the grid shows in my browser:

Try to Set
grd.DataSource = dt.DefaultView;
you must set the View to the Gridview from the DataTable..
Make sure the Table has Data.

Related

the button is not doing its supposed function

I'm having a project to create a website that connects my database to perform different functionalities. When I create the web form and connects it with the database, and when i click the button it's supposed that all the products will appear but it doesn't happen.
This is the SQL procedure:
CREATE PROC reviewOrders
AS
BEGIN
SELECT *
FROM Orders
END
And this is the c# code
protected void reviewOrders(object sender, EventArgs e)
{
string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString();
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("reviewOrders", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
and the HTML code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ReviewOrders.aspx.cs"
Inherits="GUCommerce.ReviewOrders" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="viewOrders" runat="server" OnClick ="reviewOrders" Height="45px"
Text="view orders" Width="148px" />
</div>
<p style="height: 121px">
</p>
<asp:Panel ID="x" Visible ="false" runat="server" Height="338px">
<asp:Table ID="orders" CellPadding ="4" runat="server" Height="67px" Width="316px">
</asp:Table>
</asp:Panel>
</form>
</body>
</html>
Can one please tell me what is missing?
Thanks is advance!
I would recommend using ASP Gridview instead of ASP Table. Gridviews (<asp:GridView>) are used to present data in tables. They actually get rendered as html tables. Here is how to build one using your code:
<asp:Panel ID="x" Visible="false" runat="server" Height="338px">
<%--<asp:Table ID="orders" CellPadding="4" runat="server" Height="67px" Width="316px"></asp:Table>--%>
<asp:GridView ID="gvOrders" CellPadding="4" runat="server" Height="67px" Width="316px"></asp:GridView>
</asp:Panel>
Now, in the code-behind there are a couple changes. A DataTable can be used to store the results of your query and then you can bind a DataTable to a GridView. To do this, you need a SqlDataAdapter which is shown below.
protected void reviewOrders(object sender, EventArgs e)
{
// data table variable outside of sql block
// you could also move the sql code to another method that returns a datatable
DataTable dt = null;
string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString();
using (SqlConnection conn = new SqlConnection(connStr))
{
SqlCommand cmd = new SqlCommand("reviewOrders", conn);
cmd.CommandType = CommandType.StoredProcedure;
using (cmd)
{
conn.Open();
// Use SQL Data Adapter instead of Execute Non Query
using (SqlDataAdapter _Adapter = new SqlDataAdapter(cmd))
{
// Fill DataTable with results of query
dt = new DataTable();
_Adapter.Fill(dt);
}
}
}
//
gvOrders.DataSource = dt;
gvOrders.DataBind();
}
Note: I use using(SqlConnection) and using(cmd) to handle closing the connection and command for me. Give this a shot.

GridView Design : How to add a Blank New Row in GridView after button click

I have GridView with a Button beneath it. Upon clicking the button I want to Add a new blank row just beneath the GridView
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnTest" Text="Test" runat="server" OnClick="btnTest_Click" />
</div>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<strong>Dynamic Grid</strong></td>
</tr>
<tr>
<td>
<asp:GridView ID="GrdDynamic" runat="server" AutoGenerateColumns="true"
OnRowDataBound="GrdDynamic_RowDataBound" >
</asp:GridView>
</td>
</tr>
</table>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
</body>
</html>
and the data is being populated by below way....
In pageLoad I am calling the bind
DataTable dt = GroupBudgetSetUpBLL.Instance.GetAllGroupBudgetSetUp();
GrdDynamic.DataSource = dt;
GrdDynamic.DataBind();
and in rowdatabound I am making the Grid Editable textbox.
protected void GrdDynamic_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = 1; i < e.Row.Cells.Count; i++)
{
TextBox txt = new TextBox();
string budget = e.Row.Cells[i].Text.Split('_').LastOrDefault();
string txtID = e.Row.Cells[i].Text.Split('_').FirstOrDefault() + "_" + e.Row.Cells[i].Text.Split('_').Skip(1).FirstOrDefault();
txt.ID = txtID;
txt.Text = budget;
e.Row.Cells[i].Text = "";
e.Row.Cells[i].Controls.Add(txt);
}
}
}
Now upon clicking the "Button" below the Grid I want to display a blank row just beneath the MainGrid , cells control type will be TextBox so that it remains editable.
What I could infer from your question is that you need to add a new blank row beneath the GridView (looking like the last row of the GridView is blank on button_click).
I am not sure how feasible it is to add a new Row to the databound Grid View but instead what you could do is to add a blank row in the data table like below:
Add the below code to your button1_Click():
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = GroupBudgetSetUpBLL.Instance.GetAllGroupBudgetSetUp();
DataRow myRow = dt.NewRow();
dt.Rows.InsertAt(myRow, dt.Rows.Count);
GrdDynamic.DataSource = dt;
GrdDynamic.DataBind();
}

How to bulk edit a single column in a grid view

I am working on an ASP.net application ( c#) . In it I have a grid view with columns displayed as ItemTemplates. I want to edit the values of one column.
I have an update button below the grid view. So when I click on update, the new values should be updated to the database.
I am using a list collection to bind the data to grid view.
I have no idea how to accomplish this.
Lets say you have TextBox inside the column, where the user is going to update new values. You can iterate through the gridview rows, in this manner
foreach(GridViewRow row in GridView1.Rows) {
if(row.RowType == DataControlRowType.DataRow) {
TextBox txtbx= row.FindControl("txtbx") as TextBox;
//using the txtbx you can get the new values and update then to the db
}
}
foreach(GridViewRow row in GridView1.Rows)
{
if(row.RowType == DataControlRowType.DataRow)
{
String str = ((txtbx)(row.Cells[2].Controls[0])).Text;
}
}
Check your cell value for textbox.
If you are using a GridView, are you also using a backing object (some sort of collection) to bind to the grid rows - it seems likely since you are using ItemTemplates to display them.
In this case, can you access the items you wish to change from this backing collection?
EDIT
Comment says that you're using a list to bind the grid, so why not make your changes to the list items and send those back to the database?
foreach(var listItem in MyList)
{
listItem.ThingToChange = newValueForThisProperty;
}
SubmitChangesToDatabase(MyList);
I created a full working demo and tested it:
GridBulkEdit.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="GridBulkEdit.aspx.cs" Inherits="GridBulkEdit" EnableViewState="true" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<% /*1. Enter the new value for the column to be updated in the 'NewValue' textbox
2. Check the 'UpdateThisRow' checkbox in the gridview for all rows that need to be updated.
3. Click the 'Update' button */%>
New Value: <asp:TextBox runat="server" ID="NewValue_TextBox"></asp:TextBox>
<asp:Button runat="server" ID="Update_Button" Text="Update Checked Rows With New Value" OnClick="Update_Button_Click" />
<% /* Assuming grid is bound to datasource with 2 columns:
1. 'PrimaryKeyField' - the primary key for each row
2. 'CurrentValue' - the value that we want to batch update */%>
<asp:GridView runat="server" ID="grid" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField runat="server" ID="PrmaryKeyForThisRow_HiddenField" Value='<%# Bind("PrimaryKeyField") %>' />
<asp:CheckBox runat="server" ID="UpdateThisRow_CheckBox" Checked="false" ToolTip="Check this box to update this row"/>
<asp:Label runat="server" ID="CurrentValue_Label" Text='<%# Bind("CurrentValue") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label runat="server" ID="TestOutput_Label"></asp:Label>
</form>
</body>
</html>
GridBulkEdit.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using System.Data;
public partial class GridBulkEdit : System.Web.UI.Page
{
protected void Page_PreInit(object sender, EventArgs e)
{
//Create a data table to bind the grid
DataTable DT = new DataTable();
DT.Columns.Add("PrimaryKeyField");
DT.Columns.Add("CurrentValue");
DataRow DR1 = DT.NewRow();
DR1["PrimaryKeyField"] = 1;
DR1["CurrentValue"] = "value one";
DT.Rows.Add(DR1);
DataRow DR2 = DT.NewRow();
DR2["PrimaryKeyField"] = 2;
DR2["CurrentValue"] = "value two";
DT.Rows.Add(DR2);
DataRow DR3 = DT.NewRow();
DR3["PrimaryKeyField"] = 3;
DR3["CurrentValue"] = "value three";
DT.Rows.Add(DR3);
grid.DataSource = DT;
grid.DataBind();
}
protected void Update_Button_Click(object sender, EventArgs e)
{
TestOutput_Label.Text = "";
for (int i = 0; i < grid.Rows.Count; i++)
{
HiddenField PrmaryKeyForThisRow_HiddenField = grid.Rows[i].FindControl("PrmaryKeyForThisRow_HiddenField") as HiddenField;
CheckBox UpdateThisRow_CheckBox = grid.Rows[i].FindControl("UpdateThisRow_CheckBox") as CheckBox;
if (UpdateThisRow_CheckBox.Checked)
{
UpdateRow(PrmaryKeyForThisRow_HiddenField.Value);
}
}
}
private void UpdateRow(object PrimaryKey)
{
object NewValue = NewValue_TextBox.Text;
//Execute SQL query to update row with the passed PrimaryKey with the NewValue
TestOutput_Label.Text += "<br/> Update row whose PrimaryKey is: " + PrimaryKey + " with new value: " + NewValue;
}
}

GridView displaying in display mode but not in browser ASP.NET C#

I'm relatively new to ASP.NET. My problem is I am trying to create a GridView and bind data to it by using a DataTable. My GridView element shows up in the design mode of VS 2012, but when I run it in the browser(IE), nothing displays. I have bound the data, there is clearly data entered in and I even have the EmptyDataText set to a value, so I am confused as to why NOTHING is displaying on the page from the GridView element. If I set other labels outside of GridView it displays fine, so I do not believe it is a hosting issue. Even when I turn the AutoGenerateColumns value to true, nothing happens. Any help at all would be extremely appreciated.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Tester.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>This is my page.</title>
<style type="text/css">
table {
border: 2px dashed #00FF00;
padding: inherit;
margin: inherit;
width: auto;
height: auto;
top: auto;
right: auto;
bottom: auto;
left: auto;
background-color: #0000FF;
color: #FFFFFF;
font-weight: bold;
}
</style>
</head>
<body>
<form runat="server" id="MyForm">
<asp:GridView AutoGenerateColumns="false" ID="gv" runat="server" Width="1000px" Visible="true" BorderColor="Red" EmptyDataText="WHERE IS MY DATA???">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" Text="testing123">Label from GridView</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="VenLogo" HeaderText="ID" />
<asp:BoundField DataField="VenName" HeaderText="Website" />
<asp:BoundField DataField="VenWeb" HeaderText="URL" HtmlEncode="false" />
</Columns>
</asp:GridView>
</form>
</body>
</html>
Here is my CodeBehind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Text;
namespace Tester
{
public partial class Default : System.Web.UI.Page
{
GridView gv = new GridView();
protected void Page_Load(object sender, ObjectDataSourceStatusEventArgs e)
{
if (!Page.IsPostBack)
{
gv.DataSource = Datatable();
gv.DataBind();
gv.Visible = true;
}
}
private DataTable Datatable()
{
DataTable datatable = new DataTable();
datatable.Columns.Add("VenLogo", typeof(string));
datatable.Columns.Add("VenName", typeof(string));
datatable.Columns.Add("VenWeb", typeof(string));
AddNewRow("Logo URL", "google", "http://google.com", datatable);
AddNewRow("Logo URL", "facebook", "http://facebook.com", datatable);
return datatable;
}
private void AddNewRow(string id, string website, string url, DataTable table)
{
DataRow row = table.NewRow();
row["VenLogo"] = id;
row["VenName"] = website;
//get url from GetURL method
string link = GetURL(website, url);
row["VenWeb"] = HttpUtility.HtmlDecode(link);
table.Rows.Add(row);
}
private string GetURL(string website, string url)
{
return "" + website + "";
}
}
}
Image of Split View in VS.
I am not sure, do you want to add the gridview dynamically to the page or use the one from your markup? If the first, you need to add the statement
MyForm.Controls.Add(gv);
to Page_Load. If the latter, you don´t need
GridView gv = new GridView();
but can just reference gv from markup by it´s ID.
By the way, you also have to change the parameter type of the Page_Load:
protected void Page_Load(object sender, EventArgs e)
Your local instance of gv is screwing things up. Check other parts of your partial class for a definition of gv. I'm guessing that you Page_Load code is binding to a local, private instance, instead of the protected instance that the page is using for the control. You'll want something like the following:
protected global::System.Web.UI.WebControls.GridView gv;
Your CS file code would be like this.
protected void Page_Load(object sender, EventArgs e)
{
GridView gv = new GridView();
gv.DataSource = Datatable();
gv.DataBind();
gv.Visible = true;
MyForm.Controls.Add(gv);
}
private DataTable Datatable()
{
DataTable datatable = new DataTable();
datatable.Columns.Add("VenLogo", typeof(string));
datatable.Columns.Add("VenName", typeof(string));
datatable.Columns.Add("VenWeb", typeof(string));
AddNewRow("Logo URL", "google", "http://google.com", datatable);
AddNewRow("Logo URL", "facebook", "http://facebook.com", datatable);
return datatable;
}
private void AddNewRow(string id, string website, string url, DataTable table)
{
table.Rows.Add(id, website, url);
}
private string GetURL(string website, string url)
{
return "" + website + "";
}

asp:LinqDataSource DataTable

I have a DataTable that I fill manually, ie,
newrow = dt.NewRow();
dt.Rows.Add(newrow);
and Im trying to benefit from the groupby features of LinqDataSource (as shown by Matt) by linking the LinqDataSource to the DataTable, but its just not happening.
Has anyone any experience with this?
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
public class MyData
{
public MyData(){}
private DataTable dt = new DataTable("dt");
public DataTable MyTable
{
get { return dt; }
set { dt = value; }
}
}
protected void Page_Load(object sender, EventArgs e)
{
MyData mydata = new MyData();
mydata.MyTable.Columns.Add("column1");
DataRow dr = mydata.MyTable.NewRow();
dr[0] = "some data";
mydata.MyTable.Rows.Add(dr);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:LinqDataSource
ID="LinqDataSource1"
runat="server"
ContextTypeName="MyData"
TableName="MyTable">
</asp:LinqDataSource>
<asp:GridView ID="GridView1" runat="server" DataSourceID="LinqDataSource1">
</asp:GridView>
</form>
</body>
</html>
"dt" is not the name of the table try this
DataTable dt = new DataTable("dt");
and then try this would name the table as "dt".
No that just won't work at all. The ContextTypeName property needs to be that of a Context like a LinqtoSql DataContext and the TableName is the name of the database table that is mapped in your LinqToSql DBML file. Have you tried actually following the article you link to as it gives a pretty good overview of getting LinqToSQL going.

Categories

Resources