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 + "";
}
Related
I am building a news page in a web tool using c# and visual studio. The idea is that you upload news in a specific excel format (newsID, Date, Header and text columns) and can view it in the web tool.
I managed to be able to upload the news, store it in a database table and print the news in a Gridview table with three columns: date, header and text. See the below screenshot:
My problem: is that currently I can only print plain text in the Gridview table; but I want to be able to insert hyperlinks in the text column. Is it possible to do this without hard-coding the full HTML for the link into the news message before uploading it?.
This is my default.aspx part of the table:
<div style="width: 100%; height: 400px; overflow-y: scroll">
<asp:GridView CssClass="gridview" ID="News" runat="server" AutoGenerateColumns="false" ShowHeader="False">
<Columns>
<asp:BoundField DataField="Date" ItemStyle-Width="150px" ItemStyle-VerticalAlign="Top"/>
<asp:BoundField DataField="Header" ItemStyle-VerticalAlign="Top"/>
<asp:TemplateField >
<ItemTemplate>
<div class="centered" style="width: 800px; overflow: auto; word-break: break-word; word-wrap: break-word; height: 70px;">
<%# Eval("Text")%>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
And this the c# code behind in default.aspx.cs:
public partial class _Default : Page
{
public void Page_load(object sender, EventArgs e)
{
// Enable News page only for logged in users
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
GetData();
}
}
protected void GetData()
{
News.Columns[0].Visible = true;
string Connection = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
using (SqlConnection con = new SqlConnection(Connection))
{
using (SqlCommand cmd = new SqlCommand("SELECT [Date], [Header], [Text] FROM [ART].[News Indicator] ORDER BY [NewsID] DESC"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
DataSet ds = new DataSet();
sda.Fill(ds);
News.DataSource = ds;
News.DataBind();
}
}
}
}}}
If you set the AutoGenerateColumns property to False, you have a lot of control over the columns and you can control the content.
Then use ItemTemplate with HyperLink:
<asp:GridView AutoGenerateColumns="False">
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink NavigateUrl='www.microsoft.com' Text='Whatever you want to be visible'/>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
Now the user sees on the screen the value of the Text property, but on click it takes him to page which is the value of NavigateUrl.
im trying to create a onmouseover effect in my imagebutton which is similar to this css hover effect code below.
.button:hover
{
background-color: blue;
}
Originally I have a div tag with a class that is equals to the css hover effect and inside it is my imagebutton. When im hovering the imagebutton, the background-color blue is underneath the image. Here is the image below:
As you can see from the picture above, As i hover the Ibanez logo, it only creates a blue line at the left,right and bottom border. So i decided to try to implement the hover effect directly in imagebutton, which is surprisingly difficult than the normal css approach. I've read online that you should add onmouseover in code-behind because imagebutton doesn't normally have it and should be placed in the Page_Load.
In my case, i cannot do that because my imagebutton is inside a repeater which cannot access the image button's id directly. So i ended up making an OnItemCommand to access the imagebutton. Well unfortunately my solution did not work and no hover is happening in my imagebutton. Please help me on solving this one.
Here is the aspx:
<%# Page Title="" Language='C#' MasterPageFile='~/MasterPage.master'
AutoEventWireup='true' CodeFile='GuitarBrands.aspx.cs'
Inherits='Pages_GuitarBrands' %>
<asp:Content ID='Content1' ContentPlaceHolderID='ContentPlaceHolder1'
Runat='Server'>
<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="getImageHover">
<ItemTemplate>
<div class="one-third">
<asp:ImageButton ID="brandImage" OnClick="Repeater1_OnClick"
height="250px" width="300px" runat="server" ImageUrl='<%# Eval("image")
%>' CommandArgument='<%# Eval("id") %>'
onmouseover="this.style.backgroundColor='blue';" />
</div>
</ItemTemplate>
</asp:Repeater>
</asp:Content>
Here is the aspx.cs code:
public partial class Pages_GuitarBrands : System.Web.UI.Page
{
public List<guitarBrand> brandList { get; set; }
private string brandType = "Guitar";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
DataSet ds = GetData();
Repeater1.DataSource = ds;
Repeater1.DataBind();
}
}
protected void getImageHover(object sender,RepeaterCommandEventArgs e)
{
ImageButton image = (ImageButton)e.CommandSource;
image.Attributes.Add("onmouseover","this.style.backgroundColor=\"blue\"");
}
private DataSet GetData()
{
string CS = ConfigurationManager.ConnectionStrings["brandsConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlDataAdapter da = new SqlDataAdapter("Select * from guitarBrands", con);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
protected void Repeater1_OnClick(object sender, EventArgs e)
{
ImageButton image = (ImageButton)sender;
if (image != null) {
int id = int.Parse(image.CommandArgument);
string brandName = ConnectionClassBrands.GetBrandById(id);
ConnectionClassGuitarItems.guitar = brandName;
Response.Redirect("~/Pages/GuitarItems1.aspx");
}
}
}
Try this:
protected void getImageHover(object sender,RepeaterCommandEventArgs e)
{
ImageButton image = (ImageButton)e.CommandSource;
image.Attributes.Add("class","button");
}
While in CSS, use:
<style>
.button
{
background-color: none;
}
.button:hover
{
background-color: blue;
}
</style>
Write below code in OnItemCommand event of Repeater. Hope this may help
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
ImageButton img = (ImageButton)e.Item.FindControl("brandImage");
image.Attributes.Add("onmouseover","this.style.backgroundColor=\"blue\"");
}
I'm going through a sample using drag and drop of a grid view where you can re-order the data. I'm trying to find out once the user has re-ordered the grid view how they like it how can I get the data in the first column in the order that they have changed it to. I've tried adding a bit of code to the button event to get this but it only gets the original order and not that of what the user changed it to.
ASPX Page: -
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js"></script>
<link rel="Stylesheet" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/themes/redmond/jquery-ui.css" />
<script type="text/javascript">
$(function () {
$(".drag_drop_grid").sortable({
items: 'tr:not(tr:first-child)',
cursor: 'crosshair',
connectWith: '.drag_drop_grid',
axis: 'y',
dropOnEmpty: true,
receive: function (e, ui) {
$(this).find("tbody").append(ui.item);
}
});
$("[id*=gvDest] tr:not(tr:first-child)").remove();
});
</script>
<style type="text/css">
.GridSrc td
{
background-color: #A1DCF2;
color: black;
font-size: 10pt;
font-family:Arial;
line-height: 200%;
cursor: pointer;
width:100px
}
.GridSrc th
{
background-color: #3AC0F2;
color: White;
font-family:Arial;
font-size: 10pt;
line-height: 200%;
width:100px;
}
.GridDest td
{
background-color: #eee !important;
color: black;
font-family:Arial;
font-size: 10pt;
line-height: 200%;
cursor: pointer;
width:100px
}
.GridDest th
{
background-color: #6C6C6C !important;
color: White;
font-family:Arial;
font-size: 10pt;
line-height: 200%;
width:100px
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="gvSource" runat="server" CssClass="drag_drop_grid GridSrc" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Item" HeaderText="Item"/>
<asp:BoundField DataField="Price" HeaderText="Price"/>
</Columns>
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
</body>
</html>
ASPX.CS Page: -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Item"), new DataColumn("Price") });
dt.Rows.Add("Shirt", 450);
dt.Rows.Add("Jeans", 3200);
dt.Rows.Add("Trousers", 1900);
dt.Rows.Add("Tie", 185);
dt.Rows.Add("Cap", 100);
dt.Rows.Add("Hat", 120);
dt.Rows.Add("Scarf", 290);
dt.Rows.Add("Belt", 150);
gvSource.UseAccessibleHeader = true;
gvSource.DataSource = dt;
gvSource.DataBind();
dt.Rows.Clear();
dt.Rows.Add();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gvSource.Rows)
{
Response.Write(row.Cells[0].Text.ToString());
}
}
}
You can use jquery 'tableDnD' plugin along with asp.net listview OR repeater.
Like this:
ASP.NET
<asp:Repeater>
<ItemTemplate>
<tr id='<%# Eval("ItemID") %>'>
<!-- Assign the unique key as the id of the row. -->
...
</tr>
</ItemTemplate>
</asp:Repeater>
JQuery
$(document).ready(function () {
$("#tbl").tableDnD({
onDrop: function (table, row) {
var RowIDs = '';
$('#tbl tr').each(function () {
RowIDs += $(this).attr('id') + ",";
});
$('#<%= hdnIDs.ClientID %>').val(RowIDs);
// Save the resulting sequence in a hidden field.
$('#<%= btnSaveOrder.ClientID %>').click();
// Postback the page and process the new sequence on server side.
},
onDragClass: "myDragClass",
});
});
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.
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;
}
}