C# Less obscure way to populate a DetailsView? - c#

I can't seem to bind a single GridView's row to a DetailsView properly. Currently I have this:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI.WebControls;
namespace WebApp
{
public partial class CrudGrid : System.Web.UI.UserControl
{
public const string EditCommand = "EditDialog";
public object DataSource
{
get { return Grid.DataSource; }
set { Grid.DataSource = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Grid_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
switch(e.CommandName)
{
case EditCommand:
{
int index;
if(!int.TryParse(e.CommandArgument.ToString(), out index))
throw new ArgumentException();
TableCellCollection cells = Grid.Rows[index].Cells;
Details.DataSource = new object[] { new DataSourceProvider(cells[2].Text, cells[3].Text, cells[4].Text) };
Details.DataBind();
DetailsPanel.Update();
break;
}
}
}
protected void Grid_OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
private class DataSourceProvider
{
public string Cell1 { get; set; }
public string Cell2 { get; set; }
public string Cell3 { get; set; }
public DataSourceProvider(string cell1, string cell2, string cell3)
{
Cell1 = cell1;
Cell2 = cell2;
Cell3 = cell3;
}
}
}
}
and client-side:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="CrudGrid.ascx.cs" Inherits="Firelight.WebApp.WebControls.CrudGrid" %>
<asp:UpdatePanel ID="GridPanel" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:ImageButton ID="GridInsert" ImageUrl="/images/crud/insert.png" runat="server" />
<asp:GridView ID="Grid" GridLines="None" AllowPaging="true" PageSize="15" runat="server"
OnRowCommand="Grid_OnRowCommand"
OnRowDeleting="Grid_OnRowDeleting"
>
<Columns>
<asp:ButtonField CommandName="EditDialog" ButtonType="Image" ImageUrl="/images/crud/edit.png" HeaderImageUrl="/images/crud/edit.png" />
<asp:ButtonField CommandName="Delete" ButtonType="Image" ImageUrl="/images/crud/delete.png" HeaderImageUrl="/images/crud/delete.png" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="DetailsPanel" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:DetailsView ID="Details" GridLines="None" runat="server"
AutoGenerateRows="true" DefaultMode="ReadOnly" AllowPaging="false">
</asp:DetailsView>
</ContentTemplate>
</asp:UpdatePanel>
this "works": I get a list in the detailsview enumerating the cells I manually built into a class...
what I'd actually want is something similar to
Details.DataSource = Grid.Rows[index]
enumerating the fields and their names, but that doesn't seem to work properly either.
any suggestions or ideas?
this is for a usercontrol, in case it changes anything.

why dont you simply use master/details way to do this using griview item as a control parameter to the detailsview?
<asp:DetailsView AutoGenerateRows="False" DataKeyNames="au_id" DataSourceID="SqlDataSource3"
HeaderText="Author Details" ID="DetailsView1" runat="server" Width="275px">
<Fields>
<asp:BoundField DataField="au_id" HeaderText="au_id" ReadOnly="True" SortExpression="au_id" />
<asp:BoundField DataField="au_lname" HeaderText="au_lname" SortExpression="au_lname" />
</Fields>
</asp:DetailsView>
<asp:SqlDataSource ConnectionString="<%$ ConnectionStrings:Pubs %>" ID="SqlDataSource3"
runat="server" SelectCommand="SELECT [au_id], [au_lname] FROM [authors] WHERE ([au_id] = #au_id)">
<SelectParameters>
<asp:ControlParameter ControlID="GridView1" Name="au_id" PropertyName="SelectedValue"
Type="String" />
</SelectParameters>
</asp:SqlDataSource>
Something like this:
http://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/data/GridViewMasterDetails.src

Related

Inserting multiple ID's into a SQL Table from a grid view which allows multiple check boxes to be selected

I have a grid view which I allow the user to select multiple lines via a check box, from the selected lines I want to insert a dataid into a database table.
I have used a foreach on the aspx section which looks OK however nothing is inserting on the button click.
Gridview Code.
<asp:GridView ID="GV_EyeBall" runat="server" AutoGenerateColumns="False" Font-Size="Small" Width="44%" >
<RowStyle HorizontalAlign="Center" />
<Columns>
<asp:BoundField DataField="DataId" HeaderText="DataId" ItemStyle-Width="90px" ItemStyle-Wrap="false" ItemStyle-CssClass="checkIt" SortExpression="DataId" HeaderStyle-CssClass="text-center" />
<asp:BoundField DataField="BusinessName" HeaderText="BusinessName" ItemStyle-Width="90px" ItemStyle-Wrap="false" ItemStyle-CssClass="checkIt" SortExpression="BusinessName" HeaderStyle-CssClass="text-center" ControlStyle-Font-Size="Small" />
<asp:BoundField DataField="Industry" HeaderText="Industry" ItemStyle-Width="90px" ItemStyle-Wrap="false" ItemStyle-CssClass="checkIt" SortExpression="Industry" HeaderStyle-CssClass="text-center" />
<asp:BoundField DataField="TelephoneNumber" HeaderText="TelephoneNumber" ItemStyle-Width="90px" ItemStyle-Wrap="false" ItemStyle-CssClass="checkIt" SortExpression="TelephoneNumber" HeaderStyle-CssClass="text-center" />
<asp:TemplateField ItemStyle-Width="75px" ItemStyle-Wrap="false">
<ItemTemplate>
<asp:CheckBox ID="Removechk" runat="server" ItemStyle-Width="100px" HeaderText="Remove" />
<%--<asp:HiddenField ID="DataID" runat="server" Value='<%# Eval("DataID") %>' />--%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="Silver" ForeColor="Black" />
</asp:GridView>
aspx page code
protected void Btnsubmit_Click(object sender, EventArgs e)
{
string str = string.Empty;
string strname = string.Empty;
foreach (GridViewRow gvrow in GV_EyeBall.Rows)
{
CheckBox chk = (CheckBox)gvrow.FindControl("Removechk");
if (chk.Checked)
{
Calldatabase.InsertEyeballids(Convert.ToInt32(gvrow.Cells[0].Text));
}
}
}
Page Load
protected void Page_Load(object sender, EventArgs e)
{
var eyeball = Calldatabase.Eyeball();
GV_EyeBall.DataSource = eyeball;
GV_EyeBall.DataBind();
}
It seems your grid view is getting binded again on click of your submit button on Page_Load. Since you haven't shared your Page_Load method I have implemented following working snippet based on your issue.
WebForm1.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="tempApp13.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Job" HeaderText="Job" />
<asp:BoundField DataField="Salary" HeaderText="Salary" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkRemove" runat="server" HeaderText="Remove" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="btnSubmit_Click" />
<asp:Literal ID="litMessage" runat="server" />
</form>
</body>
</html>
WebForm1.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace tempApp13
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gv.DataSource = new List<Employee>
{
new Employee { ID = 1, Name = "John", Job = "Clerk", Salary = 25000 },
new Employee { ID = 2, Name = "Allen", Job = "Clerk", Salary = 20000 },
new Employee { ID = 3, Name = "Smith", Job = "Sales", Salary = 21000 },
new Employee { ID = 4, Name = "Martin", Job = "Sales", Salary = 35000 },
new Employee { ID = 5, Name = "Bruce", Job = "Analyst", Salary = 35000 },
new Employee { ID = 6, Name = "James", Job = "Clerk", Salary = 25000 },
};
gv.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gv.Rows)
{
var chk = (CheckBox)row.FindControl("chkRemove");
if (chk.Checked)
{
litMessage.Text += row.Cells[1].Text + " ";
}
}
}
}
public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public string Job { get; set; }
public int Salary { get; set; }
}
}
I have taken a sample data source employees and binded it with grid view on Page_Load where I am checking its not IsPostBack. So on initial load the data binded to the grid view but won't binded again on page post back. Rest of the code is similar and pretty straight forward.
Hope it helps
Thanks for providing your Page_Load method. Check the following code:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack) {
var eyeball = Calldatabase.Eyeball();
GV_EyeBall.DataSource = eyeball;
GV_EyeBall.DataBind();
}
}

Search SQL Server Table Using Simple ASP.NET Search Bar

Thank you for taking the time to read my request. I am new to ASP.Net and I am trying to figure out how to implement a textbox/button that will search a SQL Server database and grab results based on queries that are 'like' an attribute. Here is what I have so far...
ASPX Main file:
<%# Page Title="" Language="C#" MasterPageFile="~/PantryAdmin.Master" AutoEventWireup="true" CodeFile="Products.aspx.cs" Inherits="RampantryF.Products" %>
<asp:Content runat="server" ContentPlaceHolderID="ContentPlaceHolder1">
<!DOCTYPE html>
<script runat="server">
public string SearchString
{
get { return TextBox4.Text; }
}
</script>
<html>
<head>
<title></title>
</head>
<body>
<div>
/*Search box*/
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
<asp:Button ID="Button1" PostBack="" runat="server" Text="Search" />
<asp:Label ID="SearchBox" runat="server" Text="Label" ForeColor="Maroon"></asp:Label>
</div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="ObjectDataSource1" AllowPaging="True" PageSize="5" AllowSorting="True">
<Columns>
<asp:BoundField DataField="PRODUCT_ID" HeaderText="PRODUCT_ID" ReadOnly="True" SortExpression="PRODUCT_ID" />
<asp:BoundField DataField="UPC_CODE" HeaderText="UPC_CODE" ReadOnly="True" SortExpression="UPC_CODE" />
<asp:BoundField DataField="PRODUCT_NAME" HeaderText="PRODUCT_NAME" ReadOnly="True" SortExpression="PRODUCT_NAME" />
<asp:BoundField DataField="PRODUCT_TYPE" HeaderText="PRODUCT_TYPE" ReadOnly="True" SortExpression="PRODUCT_TYPE" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:RampantryDB %>" SelectCommand="SELECT * FROM [PRODUCT]"></asp:SqlDataSource>
<fieldset>
<asp:DetailsView
ID="dtlDonor"
DataSourceID="ObjectDataSource1"
DefaultMode="Insert" Caption="Add Product (C)"
AutoGenerateRows="False"
runat="server">
<Fields>
<asp:BoundField DataField="PRODUCT_ID" HeaderText="PRODUCT_ID" ReadOnly="True" SortExpression="PRODUCT_ID" Visible="False" />
<asp:TemplateField HeaderText="UPC_CODE" SortExpression="UPC_CODE">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("UPC_CODE") %>'></asp:Label>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("UPC_CODE") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("UPC_CODE") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="PRODUCT_NAME" SortExpression="PRODUCT_NAME">
<EditItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("PRODUCT_NAME") %>'></asp:Label>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("PRODUCT_NAME") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("PRODUCT_NAME") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="PRODUCT_TYPE" SortExpression="PROUDUCT_TYPE">
<EditItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("PRODUCT_TYPE") %>'></asp:Label>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("PRODUCT_TYPE") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("PRODUCT_TYPE") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowInsertButton="True" />
</Fields>
</asp:DetailsView>
</fieldset>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SortParameterName="OrderBy" MaximumRowsParameterName="PageSize" DeleteMethod="Delete" InsertMethod="Insert" SelectMethod="SelectAll" TypeName="RampantryF.App_Code.BLL.PRODUCT" UpdateMethod="Update">
<DeleteParameters>
<asp:Parameter Name="PRODUCT_ID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="UPC_CODE" Type="Double" />
<asp:Parameter Name="PRODUCT_NAME" Type="String" />
<asp:Parameter Name="PRODUCT_TYPE" Type="String" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="PRODUCT_ID" Type="Int32" />
<asp:Parameter Name="UPC_CODE" Type="Double" />
<asp:Parameter Name="PRODUCT_NAME" Type="String" />
<asp:Parameter Name="PRODUCT_TYPE" Type="String" />
</UpdateParameters>
</asp:ObjectDataSource>
Behind 'Products.aspx.cs' code file:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace RampantryF
{
public partial class Products : System.Web.UI.Page
{
public SqlConnection con;
public string constr;
public void connection()
{
constr = ConfigurationManager.ConnectionStrings["PRODUCT"].ToString();
con = new SqlConnection(constr);
con.Open();
}
protected void Page_Load(object sender, EventArgs e)
{
SearchBox.Visible = false;
}
private void rep_bind()
{
connection();
string query = "select * from PRODUCT where PRODUCT_NAME like'" + TextBox4.Text + "%'";
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
connection();
string query = "select PRODUCT_NAME from PRODUCT where PRODUCT_NAME like'" + TextBox4.Text + "%'";
SqlCommand com = new SqlCommand(query, con);
SqlDataReader dr;
dr = com.ExecuteReader();
if (dr.HasRows)
{
dr.Read();
rep_bind();
GridView1.Visible = true;
TextBox4.Text = "";
SearchBox.Text = "";
}
else
{
GridView1.Visible = false;
SearchBox.Visible = true;
SearchBox.Text = "The search Term " + TextBox4.Text + " Is Not Available in the Records"; ;
}
}
}
}
BLL Products.cs File:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using RampantryF.App_Code.DAL;
namespace RampantryF.App_Code.BLL
{
public class PRODUCT
{
private int _PRODUCT_ID;
private double _UPC_CODE = 0;
private string _PRODUCT_NAME = String.Empty;
private string _PRODUCT_TYPE = String.Empty;
///Product Unique Identifier
public int PRODUCT_ID
{
get { return _PRODUCT_ID; }
}
///Product UPC_CODE
///
public double UPC_CODE
{
get { return _UPC_CODE; }
}
///Product PRODUCT_NAME
///
public string PRODUCT_NAME
{
get { return _PRODUCT_NAME; }
}
/// <summary>
/// Product PRODUCT_TYPE
/// </summary>
public string PRODUCT_TYPE
{
get { return _PRODUCT_TYPE; }
}
///retrieves all products
///
public static List<PRODUCT> SelectAll()
{
DBUtils DBUtils = new DBUtils();
return DBUtils.PRODUCTSelectAll();
}
public static List<PRODUCT> SelectAll(string OrderBy)
{
DBUtils DBUtils = new DBUtils();
return DBUtils.PRODUCTSelectAll(OrderBy);
}
///Updates a particular product
///
public static void Update(int PRODUCT_ID, double UPC_CODE, string PRODUCT_NAME, string PRODUCT_TYPE)
{
if (PRODUCT_ID < 1)
throw new ArgumentException("Product Id must be greater than 0", "id");
PRODUCT ProductToUpdate = new PRODUCT(PRODUCT_ID, UPC_CODE, PRODUCT_NAME, PRODUCT_TYPE);
ProductToUpdate.Save();
}
///inserts new product
///
public static void Insert(double UPC_CODE, string PRODUCT_NAME, string PRODUCT_TYPE)
{
PRODUCT newProduct = new PRODUCT(UPC_CODE, PRODUCT_NAME, PRODUCT_TYPE);
newProduct.Save();
}
///Deletes an Existing Product
///
public static void Delete(int PRODUCT_ID)
{
if (PRODUCT_ID < 1)
throw new ArgumentException("Product Id must be greater than 0", "id");
DBUtils DBUtils = new DBUtils();
DBUtils.PRODUCTDelete(PRODUCT_ID);
}
///validates Product information before saving Product
///properties to database
///
private void Save()
{
if (String.IsNullOrEmpty(_PRODUCT_NAME))
throw new ArgumentException("Product PRODUCT_NAME not supplied", "PRODUCT_NAME");
DBUtils DBUtils = new DBUtils();
if (_PRODUCT_ID > 0)
DBUtils.PRODUCTUpdate(this);
else
DBUtils.PRODUCTInsert(this);
}
///Intializes Product
///
public PRODUCT(int PRODUCT_ID, double UPC_CODE, string PRODUCT_NAME, string PRODUCT_TYPE)
{
_PRODUCT_ID = PRODUCT_ID;
_UPC_CODE = UPC_CODE;
_PRODUCT_NAME = PRODUCT_NAME;
_PRODUCT_TYPE = PRODUCT_TYPE;
}
public PRODUCT(double UPC_CODE, string PRODUCT_NAME, string PRODUCT_TYPE)
{
_UPC_CODE = UPC_CODE;
_PRODUCT_NAME = PRODUCT_NAME;
_PRODUCT_TYPE = PRODUCT_TYPE;
}
}
}
Any help anyone can provide is very much appreciated! Again, I am new to this, and I have been following tutorials and googling the internet trying to find a solution but cannot find one.
As of now, the page loads, but it will not actually search when the button is clicked. I would like it to change the GridView1 with all of the records into records that fill into a 'LIKE Textbox4' query.
Thank you!
You need to add click event to your search button like OnClick="Button1_Click"
<asp:Button ID="Button1" PostBack="" runat="server" Text="Search" OnClick="Button1_Click" />
also note that, inside button click event again you are calling another method to bind data to same gridview. You will lost what ever you have bind in the click event from this second method.

Hide/show gridview column based on role

Want to be able to set an "Edit" linkbutton to visible=false unless the user has a role of "Editor".
Been poking around stackoverflow and elsewhere and so far have not been able to get this to work.
Gridview:
<asp:GridView ID="GridView1" runat="server" Caption="Questions Awaiting Review" AllowSorting="True" PagerSettings-Mode="NumericFirstLast"
OnPageIndexChanging="GridView1_PageIndexChanging" CaptionAlign="Top" EmptyDataText="No Questions Pending Review."
PageSize="10" AllowPaging="true" PagerStyle-HorizontalAlign="Center" PagerStyle-Font-Size="Large" DataKeyNames="QuestionID"
OnRowCommand="GridView1_RowCommand" AutoGenerateColumns="false" AlternatingRowStyle-BackColor="#cccccc"
OnPreRender="GridView1_OnPreRender">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="QuestionID" runat="server" Text='<%# Eval("QuestionID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="KeyObjective" HeaderText="Key Objective" ItemStyle-Width="250" />
<asp:BoundField DataField="SubmitDate" HeaderText="Submitted Date" ItemStyle-Width="60" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="Details" CommandArgument='<%# Eval("QuestionID") %>' runat="server" CommandName="viewQuestion">View Question</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="Edit" CommandArgument='<%# Eval("QuestionID") %>' runat="server" CommandName="editQuestion">Edit Question</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Have changed the code behind to use OnPreRender for the gridview, which if the value is hardcoded hides the column. However when I try to retrieve the is in role of editor then the value does not seem to be evaluating correctly. Always returns false even when the user has a role of Editor.
protected void GridView1_OnPreRender(object sender, EventArgs e)
{
if (Roles.IsUserInRole("Editor"))
{
// Enter correct column index.
GridView1.Columns[4].Visible = true;
}
else
{
GridView1.Columns[4].Visible = false;
}
}
Hoping I'm missing something simple, new to asp.net so not unlikely.
Hide last column.
this.GridView1.Columns[this.GridView1.Columns.Count - 1].Visible = Roles.IsUserInRole("Editor");
You want to show/hide an entire column instead of LinkButton control. Otherwise, unauthorized user will always see a column with blank cells which is odd.
The following example will hide an entire column.
Screen Shot (Authorize vs Unauthorized)
ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DemoWebForm.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1"
runat="server"
DataKeyNames="QuestionID"
OnPreRender="GridView1_OnPreRender"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="QuestionID" runat="server" Text='<%# Eval("QuestionID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="KeyObjective" HeaderText="Key Objective" ItemStyle-Width="250" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="Edit" CommandArgument='<%# Eval("QuestionID") %>'
runat="server" CommandName="editQuestion">Edit Question</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
</body>
</html>
Code Behind
public class Question
{
public int QuestionID { get; set; }
public string KeyObjective { get; set; }
}
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = new List<Question>
{
new Question {QuestionID = 1, KeyObjective = "One"},
new Question {QuestionID = 2, KeyObjective = "Two"},
new Question {QuestionID = 3, KeyObjective = "Three"},
};
GridView1.DataBind();
}
}
protected void GridView1_OnPreRender(object sender, EventArgs e)
{
bool isEditor = true; // Business logic here
if (isEditor)
{
// Enter correct column index.
GridView1.Columns[2].Visible = false;
}
}
}
Use the LinkButton like this, with the Visibility property set from a function in code behind.
<asp:LinkButton ID="Edit" Visible='<%# ShowEditBasedOnRole() %>' CommandArgument='<%# Eval("QuestionID") %>' runat="server" CommandName="editQuestion">Edit Question</asp:LinkButton>
And then in code behind the function that returns a bool
public bool ShowEditBasedOnRole()
{
if (Roles.IsUserInRole("Editor"))
{
return true;
}
else
{
return false;
}
}
One quick modification instead of accessing the column by index. it can be accessed using header text which would not affect the code even if new column is inserted before the accessed column in future the code snippet
protected void grdResults_OnPreRender(object sender, EventArgs e)
{
TemplateField FieldToAccess= grdResults.Columns.OfType<TemplateField>
().Where(f => f.HeaderText ==
"ValidityDate").FirstOrDefault();
if (role)
FieldToAccess.Visible = false;
}

add click on ASP.net

I am working on a college project and have a gridview that I have to add more rows to.
I have two text fields and a button.
Everything seems to be fine except the button part of the code in the .cs file
What am I doing wring?
Its to make a list of Wines with an ID and a Title and a Year:
Wine.aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Wine.aspx.cs" Inherits="WineNotProject2.AdminPages.Wine" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<br /><br />
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="SqlDataSource1">
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True" SortExpression="id" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="Year" HeaderText="Year" SortExpression="Year" />
</Columns>
</asp:GridView>
<p><asp:Label ID="lblTitle" runat="server" Text="Wine Title"></asp:Label><br />
<asp:TextBox ID="txtTitle" runat="server" Width="176px"></asp:TextBox><br />
<p><asp:Label ID="lblYear" runat="server" Text="Wine Year"></asp:Label><br />
<asp:TextBox ID="txtYear" runat="server" Width="176px"></asp:TextBox><br />
</p>
<asp:Button ID="btnAdd" runat="server" Text="Add Wine" OnClick="btnAdd_Click" />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [id], [Title], [Year] FROM [Wine]">
</asp:SqlDataSource>
</asp:Content>
Wine.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WineNotProject2.AdminPages
{
public partial class Wine : System.Web.UI.Page
{
private WineEntities10 ent2 = new WineEntities10();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
RefreshGrid();
}
}
private void RefreshGrid()
{
GridView2.DataSource = ent2.Wines.ToList();
GridView2.DataBind();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
Wine w2 = new Wine();
w2.Title = txtTitle.Text;
w2.Year = txtYear.Text;
ent2.Wines.AddObject(w2);
ent2.SaveChanges();
}
}
}
UPDATE:
The error message is:
Error 3 'WineNotProject2.AdminPages.Wine' does not contain a definition for 'Year' and no extension method 'Year' accepting a first argument of type 'WineNotProject2.AdminPages.Wine' could be found (are you missing a using directive or an assembly reference?) C:\Visual Studio 2010\Projects\WineNotProject7\WineNotProject2\AdminPages\Wine.aspx.cs 30 20 WineNotProject2
I think you need to call RefreshGrid after you have added the new Wine:
protected void btnAdd_Click(object sender, EventArgs e)
{
Wine w2 = new Wine();
w2.Title = txtTitle.Text;
w2.Year = txtYear.Text;
ent2.Wines.AddObject(w2);
ent2.SaveChanges();
RefreshGrid(); // <-------
}
Maybe you also need to parse the year to int:
w2.Year = int.Parse(txtYear.Text);
The problem is you have two classes with same name Wine.
public partial class **Wine** : System.Web.UI.Page
**Wine** w2 = new **Wine**();
Rename ASP.Net page's name to WineList so that
its class name should become public partial class **WineList**
Your code was looking good ,But you miss call the RefreshGrid() end of add button
for
protected void btnAdd_Click(object sender, EventArgs e)
{
Wine w2 = new Wine();
w2.Title = txtTitle.Text;
w2.Year = txtYear.Text;
ent2.Wines.AddObject(w2);
ent2.SaveChanges();
**RefreshGrid**
}
If ent2.SaveChanges(); is not working ,then use ent2.SubmitChanges();

.NET UpdatePanel and FaceBook / Twitter Buttons

I have an UpdatePanel which has a gridview inside it. On each of the gridviewrows, within the gridview, I have a Twitter and FaceBook button.
The gridview renders fine with the buttons on page load, however, once a partial postback is done on the updatepanel the Twitter and FaceBook buttons do not render.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<!-- search controls.... -->
<asp:ImageButton ID="btnSearch" ImageUrl="~/img/button-search.gif" runat="server" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" EnableModelValidation="True"
BorderStyle="None" Font-Size="Small" GridLines="None" AllowPaging="True" ShowFooter="True"
Width="100%" OnPageIndexChanging="GridView1_PageIndexChanging">
<RowStyle CssClass="row1" />
<AlternatingRowStyle CssClass="row2" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
...
<asp:TemplateField>
<ItemTemplate>
<asp:Literal ID="ltlTwitter" runat="server" Text='<%# GetTwitterURL(Eval("ID"), Eval("SomeText")) %>'></asp:Literal>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Literal ID="ltlFacebook" runat="server" Text='<%# GetFacebookURL(Eval("ID")) %>'></asp:Literal>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" Visible="False" />
</Columns>
<EmptyDataTemplate>
<strong>There are no offers for this search criteria.</strong>
</EmptyDataTemplate>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnSearch" />
</Triggers>
</asp:UpdatePanel>
Relevant C#:
public static string GetTwitterURL(object ID, object text)
{
...
StringBuilder sb = new StringBuilder();
sb.Append("<div>");
sb.Append("<a href=\"http://twitter.com/share\" " +
"class=\"twitter-share-button\" ");
sb.AppendFormat("data-url=\"{0}?ID={1}\" ", obj.Property, oID.ToString());
sb.Append("data-via=\"xxx\" ");
sb.AppendFormat("data-text=\"{0}\"", xxx);
sb.Append("data-count=\"none\">Tweet</a>");
sb.Append("</div>");
return sb.ToString();
}
public static string GetFacebookURL(object OfferID)
{
...
return string.Format("<fb:like href=\"{0}?ID={1}\" " +
"send=\"false\" layout=\"button_count\" show_faces=\"false\" " +
"action=\"like\" font=\"tahoma\"></fb:like>", obj.Property, someInt);
}
Also, the page in question is a child page of a master page.
Here is the additional code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindOffersGrid(true);
}
}
public List<Offer> CurrentOffersDataSet
{
get
{
object o = ViewState["CurrentOfferDataSet"];
return (o == null ? new List<Offer>() : (List<Offer>)o);
}
set
{
ViewState["CurrentOfferDataSet"] = value;
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = this.CurrentOffersDataSet;
GridView1.DataBind();
}
private void BindOffersGrid(bool ApplyRandomSort)
{
List<Offer> lstOffers = Offers.GetAllBySearchCriteria(
Convert.ToInt32(ddlOfferCounty.SelectedValue),
Convert.ToInt32(ddlOfferTypes.SelectedValue),
Convert.ToDateTime(ddlOfferDate.SelectedValue), -1, true);
...
//Some filtering of the dataset with Linq
...
GridView1.DataSourceID = string.Empty;
this.CurrentOffersDataSet = lstFilteredOffers.
OrderByDescending(a => a.IsExclusive).
ThenBy(a => Guid.NewGuid()).
ToList();
GridView1.DataSource = this.CurrentOffersDataSet;
GridView1.DataBind();
}
Ok, I added the following code at the very end of my child page and now the Twitter and FaceBook like button are appearing after partial postbacks.
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(pageLoaded);
var _panels, _count;
function pageLoaded(sender, args) {
if (_panels != undefined && _panels.length > 0) {
for (i = 0; i < _panels.length; i++)
_panels[i].dispose();
}
var panels = args.get_panelsUpdated();
if (panels.length > 0) {
updateFbLike();
}
}
function updateFbLike() {
$.getScript("http://platform.twitter.com/widgets.js");
FB.XFBML.parse();
}
</script>

Categories

Resources