Here is the snippet that pulls a LOCALMACHINE\SOFTWARE
Read more...
A tech blog to core. Concentrating mainly on ASP.NET and Javascript
var employees = [
{ EmployeeID: 1, EmployeeName: "Naveen" },
{ EmployeeID: 2, EmployeeName: "Shebin" }
];
var observableEmployees = ko.observableArray( employees );But as per knockoutjs documentation,
Simply putting an object into an observableArray doesn’t make all of that object’s properties themselves observable. Of course, you can make those properties observable if you wish, but that’s an independent choice. An observableArray just tracks which objects it holds, and notifies listeners when objects are added or removed.
function MakeArrayKoObservableObjectArray(arr) {
var observableArr = [];
for (var i = 0; i < arr.length; i++) {
var observableObj = {}, obj = arr[i];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
observableObj[prop] = ko.observable(obj[prop]);
}
}
observableArr.push(observableObj);
}
return observableArr;
}
Now we can call it like this.
employees = MakeArrayKoObservableObjectArray( employees ); var observableEmployees = ko.observableArray( employees );
Happy Coding!
<form id="manager-form" action="">
<p>
<label style="display:inline-block; width: 200px;">Manager Name</label>
<input type="text" id="Manager" name="Manager" />
</p>
<p>
<input type="submit" id="saveManager" class="btn btn-primary" value="Save Sales Person" />
</p>
</form>
function SetValidationRules(){
$("#manager-form").validate({
onkeyup: false,
rules: {
Manager: {
required: true,
minlength: 3,
remote: {
url: '/Manager/IsManagerNameTaken',
type: 'POST',
dataType: 'json',
data: {
managerName: function () {
return $('#Manager').val();
}
}
}
}
},
messages: {
Manager: {
required: "Manager name is required.",
minlength: "Manager name should be 3 atleast characters."
}
}
});
}
public ActionResult IsManagerNameTaken(string managerName)
{
var result = ManagerRepository.IsManagerNameTaken(managerName) ?
"Manager name is already taken. Try another!" : "";
return Json(result);
}
$(document).on("ajaxStart", function () {
$("#jQueryAjaxmodal").modal("show");
}).on("ajaxStop", function () {
$("#jQueryAjaxmodal").modal("hide");
});
But this causes problem when one uses something like jQuery.autocomplete as ajaxStart fires on every keyup. To override this for a particular page, do this $(document).on("ajaxStart.myblock", function () {
$("#jQueryAjaxmodal").modal("show");
}).on("ajaxStop.myblock", function () {
$("#jQueryAjaxmodal").modal("hide");
});
2. Now on the DOM Ready of the page on which you wanna override this behaviour, unbind it $(document).on("ready", function () {
$(document).off(".myblock");
});
Courtesy: jQuery should I use multiple ajaxStart/ajaxStop handling
Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.
var myDateString = '01-Aug-12'; var isValidDate = !isNaN( Date.parse( myDateString ));Happy Coding!
Set Application Name as "My Demo Application"
Set Site URL as http://localhost/FacebookPost/
Type : Company, Organisation (Click on the type you want to create.
Category : Computers/Technology
Comapany Name: MyCompany
<appSettings>
<add key="AppID" value="Your App ID"/>
<add key="AppKey" value="Your App Key"/>
<add key="AppSecret" value="Your App Secret"/>
<add key="PageID" value="Your Page ID"/>
</appSettings>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Codovations Demo - Posting to Facebook Company Page</title>
<style type="text/css">
.title {
display:inline-block;
vertical-align:top;
width:100px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<label class="title">Message</label><asp:TextBox ID="MessageText" runat="server" TextMode="MultiLine" Width="200px"></asp:TextBox><br />
<label class="title">Name</label><asp:TextBox ID="NameText" runat="server" Width="200px"></asp:TextBox><br />
<label class="title">Description</label><asp:TextBox ID="DescriptionText" runat="server" TextMode="MultiLine" Width="200px"></asp:TextBox><br />
<label class="title">Picture(URL)</label><asp:TextBox ID="PictureText" runat="server" Width="200px"></asp:TextBox><br />
<label class="title">Caption</label><asp:TextBox ID="CaptionText" runat="server" Width="200px"></asp:TextBox><br />
<label class="title">Link</label><asp:TextBox ID="LinkText" runat="server" Width="200px"></asp:TextBox><br />
<label class="title"></label>
<asp:Button ID="PostToCompanyButton" runat="server"
Text="Post to Company Page" onclick="PostToCompanyButton_Click"/>
</div>
</form>
</body>
</html>
if (Request.Params["code"] != null)
{
Status.Text = "";
string accessToken = GetAccessToken(Request.Params["code"]);
FacebookAPI api = new FacebookAPI(accessToken);
JSONObject me = api.Get("me/accounts");
Dictionary dictionary = me.Dictionary;
JSONObject myPage = me.Dictionary["data"].Array
.SingleOrDefault(d => d.Dictionary["id"].String.Equals(ConfigurationManager.AppSettings["PageID"].ToString()));
if (myPage != null)
{
Dictionary parameters = Session["DataForFacebook"] as Dictionary;
Session.Remove("DataForFacebook");
string newToken = myPage.Dictionary["access_token"].String;
var app = new FacebookAPI(newToken);
var response = app.Post("me/feed", parameters);
if (response != null && response.Dictionary[""] != null)
{
Status.Text = "Data posted successfully to company page.";
ClearData();
}
else
{
Status.Text = "An error occured while posting.";
}
}
} private string GetAccessToken(string accessToken)
{
Dictionary args = GetOauthTokens(accessToken);
return args["access_token"];
}
private Dictionary GetOauthTokens(string accessToken)
{
Dictionary tokens = new Dictionary();
try
{
string url = String.Format("{0}client_id={1}&redirect_uri={2}&client_secret={3}&code={4}&scope={5}",
"https://graph.facebook.com/oauth/access_token?",
ConfigurationManager.AppSettings["AppID"].ToString(),
"http://localhost/FacebookPost/Default.aspx",
ConfigurationManager.AppSettings["AppSecret"].ToString(),
accessToken,
"publish_stream,offline_access,manage_pages");
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string retVal = reader.ReadToEnd();
foreach (string token in retVal.Split('&'))
{
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
}
catch (Exception err)
{
}
return tokens;
}
using System;
using System.Web;
using System.Data;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace yetanothercoder
{
///
/// Summary description for CreatePdf
///
public class PDFExporter
{
private readonly DataTable dataTable;
private readonly string fileName;
private readonly bool timeStamp;
public PDFExporter(DataTable dataTable, string fileName, bool timeStamp)
{
this.dataTable = dataTable;
this.fileName = timeStamp ? String.Format("{0}-{1}", fileName, GetTimeStamp(DateTime.Now)) : fileName;
this.timeStamp = timeStamp;
}
public void ExportPDF()
{
HttpResponse Response = HttpContext.Current.Response;
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".pdf");
// step 1: creation of a document-object
Document document = new Document(PageSize.A4, 10, 10, 90, 10);
// step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);
//set some header stuff
document.AddTitle(fileName);
document.AddSubject(String.Format("Table of {0}", fileName));
document.AddCreator("www.yetanothercoder.com");
document.AddAuthor("naveenj");
// step 3: we open the document
document.Open();
// step 4: we add content to the document
CreatePages(document);
// step 5: we close the document
document.Close();
}
private void CreatePages(Document document)
{
document.NewPage();
document.Add(FormatPageHeaderPhrase(dataTable.TableName));
PdfPTable pdfTable = new PdfPTable(dataTable.Columns.Count);
pdfTable.DefaultCell.Padding = 3;
pdfTable.WidthPercentage = 100; // percentage
pdfTable.DefaultCell.BorderWidth = 2;
pdfTable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
foreach (DataColumn column in dataTable.Columns)
{
pdfTable.AddCell(FormatHeaderPhrase(column.ColumnName));
}
pdfTable.HeaderRows = 1; // this is the end of the table header
pdfTable.DefaultCell.BorderWidth = 1;
foreach (DataRow row in dataTable.Rows)
{
foreach (object cell in row.ItemArray)
{
//assume toString produces valid output
pdfTable.AddCell(FormatPhrase(cell.ToString()));
}
}
document.Add(pdfTable);
}
private static Phrase FormatPageHeaderPhrase(string value)
{
return new Phrase(value, FontFactory.GetFont(FontFactory.TIMES, 10, Font.BOLD, new BaseColor(255, 0, 0)));
}
private static Phrase FormatHeaderPhrase(string value)
{
return new Phrase(value, FontFactory.GetFont(FontFactory.TIMES, 8, Font.UNDERLINE, new BaseColor(0, 0, 255)));
}
private Phrase FormatPhrase(string value)
{
return new Phrase(value, FontFactory.GetFont(FontFactory.TIMES, 8));
}
private string GetTimeStamp(DateTime value)
{
return value.ToString("yyyyMMddHHmmssffff");
}
}
}
protected void ExportToPDFLink_Click(object sender, EventArgs e)
{
PDFExporter pdf = new PDFExporter(GetCostumers(), "customer", true);
pdf.ExportPDF();
}
SQLite is a in-process library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine.
using System.Data.SQLite6. Create a default page in your application and place a gridview in that
<asp:GridView ID="CustomersGrid" runat="server"> </asp:GridView>
private void BindCustomerGrid()
{
string commandText = "SELECT * FROM Customers";
string path_to_db = System.IO.Path.Combine(Server.MapPath("."), "App_Data", "Northwind.sqlite3");
string connectionString = String.Format("Data Source={0};Version=3;", path_to_db);
DataTable dataTable = new DataTable();
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
using (SQLiteCommand cmd = new SQLiteCommand(commandText, connection))
{
cmd.CommandType = CommandType.Text;
using (SQLiteDataAdapter adapter = new SQLiteDataAdapter(cmd))
{
adapter.Fill(dataTable);
}
}
}
CustomersGrid.DataSource = dataTable;
CustomersGrid.DataBind();
}
<asp:GridView ID="gvProducts" runat="server"
AllowPaging="True"
AutoGenerateColumns="False"
DataKeyNames="ProductID"
OnPageIndexChanging="gvProducts_PageIndexChanging"
OnRowDataBound="gvProducts_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ProductID" HeaderText="ProductID" InsertVisible="False"
ReadOnly="True" SortExpression="ProductID" />
<asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
</Columns>
</asp:GridView>
<asp:GridView ID="gvCustomers" runat="server"
AllowPaging="True"
AutoGenerateColumns="False"
DataKeyNames="CustomerID"
OnPageIndexChanging="gvCustomers_PageIndexChanging"
OnRowDataBound="gvCustomers_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CustomerID" HeaderText="ID" InsertVisible="False" />
<asp:BoundField DataField="CompanyName" HeaderText="CompanyName" />
</Columns>
</asp:GridView>
private List<int> ProductIDs
{
get
{
if (this.ViewState["ProductIDs"] == null)
{
this.ViewState["ProductIDs"] = new List<int>();
}
return this.ViewState["ProductIDs"] as List<int>;
}
}
private List<string> CustomerIDs
{
get
{
if (this.ViewState["CustomerIDs"] == null)
{
this.ViewState["CustomerIDs"] = new List<string>();
}
return this.ViewState["CustomerIDs"] as List<string>;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid(gvProducts, "Products");
BindGrid(gvCustomers, "Customers");
}
}
protected void gvProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
foreach (GridViewRow gvr in gvProducts.Rows)
{
CheckBox chkSelect = gvr.FindControl("chkSelect") as CheckBox;
if (chkSelect != null)
{
int productID = Convert.ToInt32(gvProducts.DataKeys[gvr.RowIndex]["ProductID"]);
if (chkSelect.Checked && !this.ProductIDs.Contains(productID))
{
this.ProductIDs.Add(productID);
}
else if (!chkSelect.Checked && this.ProductIDs.Contains(productID))
{
this.ProductIDs.Remove(productID);
}
}
}
gvProducts.PageIndex = e.NewPageIndex;
BindGrid(gvProducts, "Products");
}
protected void gvProducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridViewRow gvr = e.Row;
if (gvr.RowType == DataControlRowType.DataRow)
{
CheckBox chkSelect = gvr.FindControl("chkSelect") as CheckBox;
if (chkSelect != null)
{
int productID = Convert.ToInt32(gvProducts.DataKeys[gvr.RowIndex]["ProductID"]);
chkSelect.Checked = this.ProductIDs.Contains(productID);
}
}
}
protected void gvCustomers_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
foreach (GridViewRow gvr in gvCustomers.Rows)
{
CheckBox chkSelect = gvr.FindControl("chkSelect") as CheckBox;
if (chkSelect != null)
{
string customerID = gvCustomers.DataKeys[gvr.RowIndex]["CustomerID"].ToString();
if (chkSelect.Checked && !this.CustomerIDs.Contains(customerID))
{
this.CustomerIDs.Add(customerID);
}
else if (!chkSelect.Checked && this.CustomerIDs.Contains(customerID))
{
this.CustomerIDs.Remove(customerID);
}
}
}
gvCustomers.PageIndex = e.NewPageIndex;
BindGrid(gvCustomers, "Customers");
}
protected void gvCustomers_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridViewRow gvr = e.Row;
if (gvr.RowType == DataControlRowType.DataRow)
{
CheckBox chkSelect = gvr.FindControl("chkSelect") as CheckBox;
if (chkSelect != null)
{
string customerID = gvCustomers.DataKeys[gvr.RowIndex]["CustomerID"].ToString();
chkSelect.Checked = this.CustomerIDs.Contains(customerID);
}
}
}
private DataTable PopulateData(string tableName)
{
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString))
{
string sql = String.Format("SELECT * FROM {0}", tableName);
using (SqlDataAdapter adap = new SqlDataAdapter(sql, conn))
{
adap.Fill(dt);
}
}
return dt;
}
private void BindGrid(GridView gvTemp, string tableName)
{
gvTemp.DataSource = PopulateData(tableName);
gvTemp.DataBind();
}
Collation refers to a set of rules that determine how data is sorted and compared.
Character data is sorted using rules that define the correct character sequence,
with options for specifying
1) case-sensitivity,
2) accent marks,
3) kana character types and
4)character width.
Case sensitivity
If A and a, B and b, etc. are treated in the same way then it is case-insensitive. A computer treats A and a differently because it uses ASCII code to differentiate the input. The ASCII value of A is 65, while a is 97. The ASCII value of B is 66 and b is 98.
Accent sensitivity
If a and á, o and ó are treated in the same way, then it is accent-insensitive. A computer treats a and á differently because it uses ASCII code for differentiating the input. The ASCII value of a is 97 and áis 225. The ASCII value of o is 111 and ó is 243.
Kana Sensitivity
When Japanese kana characters Hiragana and Katakana are treated differently, it is called Kana sensitive.
Width sensitivity
When a single-byte character (half-width) and the same character when represented as a double-byte character (full-width) are treated differently then it is width sensitive.
ALTER TABLE test_table ALTER COLUMN mytext VARCHAR(50) COLLATE Arabic_CI_AIStep 2
protected void myButton_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["forums_ConnectionString"].ConnectionString))
{
conn.Open();
string sql = String.Format("INSERT INTO test_table (mytext) VALUES (N'{0}')",
mytext.Text.Trim());
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.ExecuteNonQuery();
}
}
}
Please note that I have put N' before the value.<script type="text/javascript">
//<![CDATA[
if (window.top !== window.self) {
document.write = "";
window.top.location = window.self.location;
setTimeout(function () {
document.body.innerHTML = '';
}, 1);
window.self.onload = function (evt) {
document.body.innerHTML = '';
};
}
//]]>
</script>
function htmlEncode(value){
return $('<div/>').text(value).html();
}
function htmlDecode(value){
return $('<div/>').html(value).text();
}
DataTable dataTable = new DataTable
{
Columns = {
{"ID", typeof(int)},
{"Name", typeof(string)},
"Location"
},
TableName="NaveenTest"
};
dataTable.Rows.Add(1, "Naveen", "Coder");
Please note that if you don't specify the type it will automatically be converted to string. See how "Location" is initialisedAnd my old method
DataTable dtOld = new DataTable("NaveenTest");
dtOld.Columns.Add("MyID", typeof(int));
dtOld.Columns.Add("Name");
dtOld.Columns.Add("Location");
DataRow drOld = new DataRow();
drOld[0] = 1;
drOld[1] = "Naveen";
drOld[2] = "Coder";
dtOld.Rows.Add(drOld);
GrayScale - Converts the colors of the object to 256 shades of gray.An example will be
.greyscale_filter{
filter: gray;
}
or.greyscale_filter{
-ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)";
filter: progid:DXImageTransform.Microsoft.BasicImage(grayscale=1);
}
Here the second method is more advanced and must have Internet Explorer 5.5 or later to work properly.Why does not the GrayScale filter work with browsers like Chrome, Firefox and Safari?
Simple. The filter is specific to IE only.
Grayscale.js is an experimental attempt to emulate Microsoft's
proprietary 'grayscale' filter (available in most IE versions).
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>than
<script type="text/javascript" src="/js/jQuery.min.js"></script>3. Add a small javascript snippet like this
$(document).ready(function(){
$('img.greyonhover').hover(function(){
grayscale(this);
}, function(){
grayscale.reset(this);
})
});
4. Assign the class="greyonhover" for the image you want to implement grayscale effect onhover <img class="greyonhover" src="images/naveenj-thumb.jpg" />
<asp:GridView ID="gvwProducts" runat="server"
AutoGenerateColumns="False"
DataKeyNames="ProductID"
DataSourceID="sdsProducts"
OnRowDataBound="gvwProducts_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Contact Name">
<ItemTemplate>
<asp:Label ID="lblProductName" runat="server"
Text='<%#Eval("ProductName") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Stock">
<ItemTemplate>
<asp:Label ID="lblunitsInStock" runat="server"
Text='<%#Eval("UnitsInStock") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<SelectedRowStyle ForeColor="Green" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
</asp:GridView>
<asp:SqlDataSource ID="sdsProducts" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT ProductID, ProductName, UnitsInStock FROM Products"
SelectCommandType="Text">
</asp:SqlDataSource>
protected void gvwProducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//e.Row.Attributes["onmouseover"] = "this.style.color='DodgerBlue';this.style.cursor='hand';";
e.Row.Attributes["onmouseover"] = "javascript:return ChangeRowColor('m_over', this.style)";
//e.Row.Attributes["onmouseout"] = "this.style.color='Black';";
e.Row.Attributes["onmouseout"] = "javascript:return ChangeRowColor('m_out', this.style)";
e.Row.Attributes["onclick"] = "javascript:return __doPostBack('" + gvwProducts.ClientID.Replace('_','$') + "', 'Select$" + e.Row.RowIndex + "');";
e.Row.ToolTip = "Click on the row to select it";
}
}
System.ArgumentException: Invalid postback or callback argument. Event validation is enabled usingin configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation
protected override void Render(HtmlTextWriter writer)
{
// .NET will refuse to accept "unknown" postbacks for security reasons.
// Because of this we have to register all possible callbacks
// This must be done in Render, hence the override
for (int i = 0; i < gvwProducts.Rows.Count; i++)
{
Page.ClientScript.RegisterForEventValidation(new System.Web.UI.PostBackOptions(this.gvwProducts, "Select$" + i.ToString()));
}
// Do the standard rendering stuff
base.Render(writer);
}
Now compare the RowDataBound event to first example and you note some changes in
the way the row attributes for onmouseover and onmouseout are set.
(Check the commented lines in the RowDataBound event)
What we do here is to set a foreground color "Green" to the Selected Row and persists that color
onmouseout and onmouseover of the selected row.
Inorder to achieve that, place this javascript function on the page.
function ChangeRowColor(eventtype, rowStyle){
if(rowStyle.color.toLowerCase() != "green"){
if(eventtype == "m_over"){
rowStyle.color='DodgerBlue';
rowStyle.cursor='pointer';
}
else{
rowStyle.color='Black';
}
}
else{
rowStyle.cursor='default';
}
}
Now some developers may get the
__doPostBack(...) object requiredTo circumvent this error place these on the ASPX Page Two Hidden Fields
<input type ="hidden" name ="__EVENTTARGET" value ="" /> <input type ="hidden" name ="__EVENTARGUMENT" value ="" />Javascript Function
//
protected void gvwProducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.color='DodgerBlue';this.style.cursor='hand';";
e.Row.Attributes["onmouseout"] = "this.style.color='Black';";
e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.gvwProducts, "Select$" + e.Row.RowIndex);
e.Row.ToolTip = "Click on the row to select it";
}
}
System.ArgumentException: Invalid postback or callback argument.
Event validation is enabled usingin configuration
or <%@ Page EnableEventValidation="true" %> in a page.
For security purposes, this feature verifies that arguments to postback or callback events originate
from the server control that originally rendered them.
If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method
in order to register the postback or callback data for validation.
protected override void Render(HtmlTextWriter writer)
{
// .NET will refuse to accept "unknown" postbacks for security reasons.
// Because of this we have to register all possible callbacks
// This must be done in Render, hence the override
for (int i = 0; i < gvwProducts.Rows.Count; i++)
{
Page.ClientScript.RegisterForEventValidation(new System.Web.UI.PostBackOptions(gvwProducts, "Select$" + i.ToString()));
}
// Do the standard rendering stuff
base.Render(writer);
}
Here I am posting the ASPX markup of the GridView also
The ASPX
<asp:GridView ID="gvwProducts" runat="server"
AutoGenerateColumns="False"
DataKeyNames="ProductID"
DataSourceID="sdsProducts"
OnRowDataBound="gvwProducts_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Contact Name">
<ItemTemplate>
<asp:Label ID="lblProductName" runat="server"
Text='<%#Eval("ProductName") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Stock">
<ItemTemplate>
<asp:Label ID="lblunitsInStock" runat="server"
Text='<%#Eval("UnitsInStock") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
</asp:GridView>
<asp:SqlDataSource ID="sdsProducts" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT ProductID, ProductName, UnitsInStock FROM Products"
SelectCommandType="Text">
</asp:SqlDataSource>
Just paste the last xml snippet on ASPX and first two code snippets on cs page.
Change the connectionstring to the one you have and run the code to see the result.
We are not finished yet
From time to time, some developers will experience the "__doPostBack object expected" error in the page Postback.
This occurs at the second time we try to fire the row click event
The Reason
We add onclick feature for GridView in the RowDataBound event using ClientScript.GetPostBackClientHyperlink(...) But RowDataBound event gets fired only the first time(at !IsPostBack). This creates the __doPostBack() function when the page is first time loaded. Now from the second time onwards(at IsPostBack) RowDataBound doesn't get fired. So no ClientScript.GetPostBackClientHyperlink(...) is called and no __doPostBack() function is createdThe solution. Just place this line under Page_Load event
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.GetPostBackClientHyperlink(this, "");
}
Happy Coding!
For Better understanding please read Selectable GridViewRow using JavaScript
Points to Note:
1. I have given a SelectedRowStyle to show that the row is actually selected by giving it a different color.
2. The table used is Products from Microsoft's Sample DataBase Northwind
<asp:GridView ID="GridView1" runat="server"
AllowPaging="true"
AllowSorting="true"
AutoGenerateColumns="false"
DataKeyNames="ProductID"
PageSize="10"
OnPageIndexChanging="GridView1_PageIndexChanging"
OnSorting="GridView1_Sorting">
<Columns>
<asp:TemplateField HeaderText="ID" SortExpression="ProductID">
<ItemTemplate>
<asp:Label ID="lblProductID" runat="server"
Text='<%#Eval("ProductID") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" SortExpression="ProductName">
<ItemTemplate>
<asp:Label ID="lblProductName" runat="server"
Text='<%#Eval("ProductName") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Stock" SortExpression="UnitsInStock">
<ItemTemplate>
<asp:Label ID="lblUnitsInStock" runat="server"
Text='<%#Eval("UnitsInStock") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
private const string ASCENDING = " ASC";
private const string DESCENDING = " DESC";
static private DataView dvProducts;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
dvProducts = new DataView(GetProductsFromDataTable());
BindGridView();
}
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
dvProducts.Sort = sortExpression + DESCENDING;
BindGridView();
}
else
{
GridViewSortDirection = SortDirection.Ascending;
dvProducts.Sort = sortExpression + ASCENDING;
BindGridView();
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindGridView();
}
private void BindGridView()
{
GridView1.DataSource = dvProducts;
GridView1.DataBind();
}
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
private DataTable GetProductsFromDataTable()
{
DataTable dtProductsTemp = new DataTable();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString))
{
using (SqlDataAdapter adapProducts = new SqlDataAdapter("Select * from Products", conn))
{
adapProducts.Fill(dtProductsTemp);
}
}
return dtProductsTemp;
}
using System.Data.SqlClient;
|
|
|
|
Codes in ASP.NET with C#. Absolutely loves jQuery. Contributor at forums.asp.net as naveenj. A die hard Jeff Atwood fan-boy. Adores Jon Skeet to a fault. |
|
|
| |
|
|
Visitor Stats |