Google Brother Up

2008/12/19

Split a string separated by ";" and place in an array

How to split a string like this ";1;2;3;4;5;6" and put in on an array?

string mstrStream = mstrSelectedRowsStream.Remove(0,1); // to remove the semicolon on the extreme left

char chSep = ';';
string[] arrStr = mstrStream.Split(chSep);


How to get each number back from that array?

for (int i = 0; i <>
{
     string s = arrStr[i].ToString();
}

145 unique visitors

2008/12/12

Fundas on Server Paths

1. Server.MapPath(strPath)

2. (asp:Image ImageUrl=“~/images/pictures.gif runat=“server“/)

3. TextWriter tw = new StreamWriter(~"\\servername\test.txt");
tw.WriteLine("test1");
tw.Close();


4. @"C:\test\source\folder3.cs")

143 unique visitors

How to get a Path & Xml file values into a Dataset

string dtxmlFilePath = "datatypes.xml";

FileStream dtFileStream = new FileStream(Server.MapPath(dtxmlFilePath), FileMode.Open, FileAccess.Read);

StreamReader dtXmlStream = new StreamReader(dtFileStream);

ds.Tables[0].ReadXml(dtXmlStream);

dtFileStream.Close();

143 unique visitors

Convert a string to Proper Case or Sentence Case

using System.Globalization;

CultureInfo cc = new CultureInfo("");
TextInfo ti = cc.TextInfo;
ti.ToTitleCase(mlstSelectedColumn
.ColumnDataTypeCSharp)

143 unique visitors

2008/11/26

Sys.WebForms.PageRequestManagerServerErrorException:

Problem: - Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 500

Solution: -

In the @Page tag set 

ValidateRequest="false"

When does it occur?

This normally occurs when there is 
1) a multiline textbox in the page
2) an update panel in the page inside which the multiline textbox resides

121 unique visitors

2008/10/31

Paging Code Behind

protected void gvColumnList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {        
        gvColumnList.PageIndex = e.NewPageIndex;
        gvColumnList.DataSource = ViewState["vsGridView"];
        gvColumnList.DataBind();                        
    }


106 unique visitors

2008/10/27

All Databases and All Tables

  • Select All Databases from a Server (this is a system stored procedure)
sp_databases

  • Select All Tables from a Particular Database

select name from sysobjects WHERE type = 'U'

106 unique visitors

2008/09/10

A Master Page & A Content Page

A Master page defines the layout to be used by all pages based on the Master. It’s the overall parent that
controls your layout, specifying how big your header will be on every page, where your navigation features
will be placed, and the text to display in the footer on every page—a bit like a cookie cutter for
each page. The Master page contains some of the content available to each page on the site, so standard
copyright footer text can be defined here, along with positioning the main site logo at the top of the
page. After the standard features of the Master are defined, you then add some placeholders—named
regions on a page that define where content that varies from page to page will be positioned.

A Content page is a page based on a Master, and is where you add the content for each page on a site that 
varies from page to page. The Content page contains text, HTML, and controls within
tags. When the Content page is requested, its content is combined with a copy of the Master page, with
the specific content defined in the Content page placed within the specified placeholder on the Master
page. Then the whole package is delivered to the browser, as shown in Figure 2-1.

86 unique visitors

2008/09/08

Some AJAX Sites

http://en.wikipedia.org/wiki/XMLHttpRequest
http://en.wikipedia.org/wiki/AJAX
http://www.ajaxpro.info/lesson/1/
http://weblogs.asp.net/mschwarz/archive/2007/04/10/jquery-and-ajax-net-professional-ajaxpro.aspx
http://malakablog.wordpress.com/2008/07/16/using-ajax-pro-step-by-step/
http://ajaxpro.info/Examples/Special/keypress.aspx
http://weblogs.asp.net/mschwarz/default.aspx
http://dotnetslackers.com/Community/blogs/sonukapoor/archive/2007/04/19/AjaxPro-Rocks_2100_.aspx
http://www.schwarz-interactive.de/quickguide.aspx
http://www.schwarz-interactive.de/quickguide.aspx
http://munich.schwarz-interactive.de/session.aspx
http://munich.schwarz-interactive.de/autocomplete.aspx
http://ajaxpro.info/Examples/Special/keypress.aspx
http://www.schwarz-interactive.de/quickguide.aspx
http://free-ebook-download-links-gw.blogspot.com/2008/06/introducing-microsoft-aspnet-ajax-pro.html

http://ajaxpro.schwarz-interactive.de/ (good)

http://ajax.phpmagazine.net/2006/09/new_ajaxpro_java_edition.html
D:\Vaijayanta-BACKUP\Back-Up-For-XP\VAIJAYANTA\IMPORTANT\Study Materials All\Study Materials 2007 August to December\Ajax\CSharpSample
http://tricks-for-new-bloggers.blogspot.com
http://www.codeproject.com/KB/aspnet/DynamicControls.aspx
http://extjs.com/forum/archive/index.php/t-2641.html
http://extjs.com/forum/showthread.php?t=2641
http://69.10.233.10/KB/cpp/ASPNet_Ajax.aspx
http://69.10.233.10/KB/cpp/ASPNet_Ajax.aspx?fid=421153&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2483447#xx2483447xx
http://w3schools.com/html/html_forms.asp
http://news.hping.org/comp.lang.javascript.archive/17790.html
http://www.ajaxlab.com/index.php?c=AjaxProNET
http://munich.schwarz-interactive.de/default.aspx

http://www.codeproject.com/KB/ajax/AjaxValidation.aspx (good)

http://www.aspcode.net/AjaxNET-part-3.aspx (good)
http://www.codeproject.com/KB/ajax/AjaxValidation.aspx

81 unique visitors

AJAX .NET Examples and Concepts

This webpage has a lot of examples: -

http://www.asp.net/ajax/documentation/live/overview/UpdatePanelOverview.aspx

81 unique visitors

AJAX PRO Concept and Example

AJAX PRO


1. In web.config file add the tag below under (system.web) tag: -

(httpHandlers)
(add verb="POST,GET" path="ajaxpro/*.ashx" type="AjaxPro.AjaxHandlerFactory, AjaxPro.2"/)
(/httpHandlers)

2. Write the TestAjaxPro.aspx file: -

(html xmlns="http://www.w3.org/1999/xhtml" )
(head runat="server")
(title)Test Ajax Pro Page(/title)

(script type="text/javascript")
function getServerTime() // being called from (body)
{
TestAjaxPro.GetServerTimeAjax(getServerTime_callback); // asynchronous call
}

function getServerTime_callback(res) // being called from inside GetServerTimeAjax() parameter
{
alert(res.value);
}
(/script)

(/head)
(body onload="javascript:getServerTime();")
(form id="form1" runat="server" )
(div)

(/div)
(/form)
(/body)
(/html)


3. Write the TestAjaxPro.aspx.cs file: -

using AjaxPro;

public partial class TestAjaxPro : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
AjaxPro.Utility.RegisterTypeForAjax(typeof(TestAjaxPro)); //
}

[AjaxPro.AjaxMethod]
public DateTime GetServerTimeAjax() // being called from getServerTime()
{
return DateTime.Now;
}
}

4. Run the code.


81 unique visitors

2008/08/14

ConnectionString in Web.Config

(configuration)
(appSettings)
(add key="mstrConnectionString" value="user id=abcd; password=1234; server=VAIJAYANTA-PC\SQLEXPRESS; database="VaijayantaTest" /)
(/appSettings)
(/configuration)

or

(configuration)
(connectionStrings)
(add name="mstrConnectionString" connectionString="user id=abcd; password=1234 server=VAIJAYANTA-PC\SQLEXPRESS; database="VaijayantaTest" /)
(/connectionStrings)
(/configuration)

string StrCon;

StrCon = ConfigurationSettings.AppSettings.Get("mstrConnectionString");

Sqlconnection conn = new SqlConnection(StrCon );
conn.Open();
SqlCommand cmd = new SqlCommand(select,conn);

rest follows.........

72 unique visitors

2008/08/08

What is DDL, DML, DCL, TCL in SQL ?

The Data Definition Language (DDL) includes: -
CREATE TABLE - creates new database table
ALTER TABLE - alters or changes the database table
DROP TABLE - deletes the database table
CREATE INDEX - creates an index or used as a search key
DROP INDEX - deletes an index


The Data Manipulation Language (DML) includes: -
SELECT - extracts data from the database
UPDATE - updates data in the database
DELETE - deletes data from the database
INSERT INTO - inserts new data into the database

The Data Control Language (DCL) includes: -
GRANT – gives access privileges to users for database
REVOKE – withdraws access privileges to users for database

The Transaction Control Language (TCL) includes: -
COMMIT – saves the work done
ROLLBACK - restore the database to original since the last COMMIT

70 unique visitors

2008/08/05

How to write a Database Connection in Dot Net

---------------------------------------------------------------------------

source = "server=(local); integrated security=SSPI; database=Northwind";

select = "select * from Customers";
Sqlconnection conn = new SqlConnection(source);

conn.Open();

SqlCommand cmd = new SqlCommand(select,conn);

int rowsReturned = cmd.ExecuteNonQuery(); //returns no of rows affected

---------------------------
SqlDataReader reader = cmd.ExecuteReader();

while(reader.Read())

{

ConsoleWriteline(reader[0], reader[1]); //returns a set of values

} // by iterating through records

-------------------------


object o = cmd.ExecuteScalar();

Console.WriteLine(o); // returns a column

-----------------

XmlReader xr = cmd.ExecuteXmlReader();

xr.Read(); // returns a XmlReaderObject

--------------

SqlDataAdapter da = new SqlDataAdapter(select, conn);

DataSet ds = new DataSet();

da.Fill(ds,"Customers"); //runtime schema generation
---------------------------------------------------------------------------

68 unique visitors

A Database Trigger

A database trigger is procedural code that is automatically executed in response to certain events on a particular table in a database. Triggers can restrict access to specific data, perform logging, or audit data modifications.

Difference between a trigger and a stored procedure

1- when you create a trigger you have to identify event and action of your trigger but when you create s.p you don't identify event and action

2-trigger is run automatically if the event is occured but s.p don't run automatically but you have to run it manually

3- within a trigger you can call specific s.p but within a s.p you cann;t call atrigger

68 unique visitors

2008/07/31

SQL Server Database ConnectionString

string strCon;
SqlConnection objCon = new SqlConnection();
string mstrConnectionstring = String.Empty;
public DataObject()
{
objCon = new SqlConnection();
strCon = ConfigurationSettings.AppSettings.Get("mstrConnectionstring");
objCon = new SqlConnection(strCon);
objCon.Open();
----------------------------------------
Inside WebConfig. Replace the ( and ) by <>.

(appSettings)(add key="mstrConnectionstring" value="user id= ab;password=**********; server=VAIJAYANTA-PC\SQLEXPRESS; database = Vaijayanta-Test")(/add)(/appSettings)

65 unique visitors

2008/07/08

Export Gridview to Pdf

Error: - The document has no pages.
Soution: -Check the column name of your gridview. Whether they match with the ones you send to the data table or not. If they match. Then this error will not be shown.
Export Gridview to Pdf: -
1) First of all add reference the dll file called itextsharp.dll to your solution under References.
It can be obtained from: -

2) Then write the code below: -
using iTextSharp;using iTextSharp.text;using iTextSharp.text.pdf;
protected void btnExportToPdf_Click(object sender, EventArgs e) { ExportToPDF(); }
private void ExportToPDF() { Document document = new Document(PageSize.A4, 0, 0, 50, 50); System.IO.MemoryStream msReport = new System.IO.MemoryStream();
try { // creation of the different writers PdfWriter writer = PdfWriter.GetInstance(document, msReport);
// we add some meta information to the document document.AddAuthor("Vaichatt"); document.AddSubject("Export to PDF");
document.Open();
iTextSharp.text.Table datatable = new iTextSharp.text.Table(5);
datatable.Padding = 2; datatable.Spacing = 0;
//float[] headerwidths = { 6, 20, 32, 18, 8, 8, 8 }; float[] headerwidths = { 10, 50, 10, 15, 15 }; datatable.Widths = headerwidths;
// the first cell spans 7 columns // the first cell spans 5 columns Cell cell = new Cell(new Phrase("Manage Category Report", FontFactory.GetFont(FontFactory.HELVETICA, 16, Font.BOLD))); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.Leading = 30; //cell.Colspan = 7; cell.Colspan = 5; cell.Border = Rectangle.NO_BORDER; cell.BackgroundColor = new iTextSharp.text.Color(System.Drawing.Color.Gray); datatable.AddCell(cell);
// These cells span 2 rows datatable.DefaultCellBorderWidth = 1; datatable.DefaultHorizontalAlignment = 1; datatable.DefaultRowspan = 2; datatable.AddCell("Status"); datatable.AddCell(new Phrase("Category Name", FontFactory.GetFont(FontFactory.HELVETICA, 14, Font.NORMAL))); datatable.AddCell("Edit"); datatable.AddCell("Delete"); datatable.AddCell("Products");
// This cell spans the remaining 3 columns in 1 row //datatable.DefaultRowspan = 1; //datatable.DefaultColspan = 3; //datatable.AddCell("Just Put Anything");
// These cells span 1 row and 1 column //datatable.DefaultColspan = 1; //datatable.AddCell("Col 1"); //datatable.AddCell("Col 2"); //datatable.AddCell("Col 3");
datatable.DefaultCellBorderWidth = 1; datatable.DefaultRowspan = 1;
for (int i = 1; i < dgdManageCategory.Rows.Count; i++) { datatable.DefaultHorizontalAlignment = Element.ALIGN_LEFT; //datatable.AddCell(i.ToString()); //datatable.AddCell("This is my name."); //datatable.AddCell("I have a very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very long long address."); //datatable.AddCell("0123456789");
//datatable.DefaultHorizontalAlignment = Element.ALIGN_CENTER; //datatable.AddCell("No"); //datatable.AddCell("Yes"); //datatable.AddCell("No");
CheckBox cbIsActive = (CheckBox)dgdManageCategory.Rows[i].FindControl("cbIsActive"); datatable.AddCell(Convert.ToString(cbIsActive.Checked ));
Label lblCategoryName = (Label)dgdManageCategory.Rows[i].FindControl("lblCategoryName"); datatable.AddCell(lblCategoryName.Text);
//Label lblCatName = (Label)dgdManageCategory.Rows[i].FindControl("lblCatName"); //datatable.AddCell(lblCatName.ToString());
Button btnEdit = (Button)dgdManageCategory.Rows[i].FindControl("lbnEdit"); datatable.AddCell(btnEdit.Text);
Button btnDelete = (Button)dgdManageCategory.Rows[i].FindControl("lbnDelete"); datatable.AddCell(btnDelete.Text);
Button btnProducts = (Button)dgdManageCategory.Rows[i].FindControl("lbnProducts"); datatable.AddCell(btnProducts.Text); }
document.Add(datatable); } catch (Exception e) { string s = e.Message; Console.Error.WriteLine(e.Message); }
// we close the document document.Close();
Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename=Export.pdf"); Response.ContentType = "application/pdf"; Response.BinaryWrite(msReport.ToArray()); Response.End();
//http://july-code.blogspot.com/2008/06/export-gridview-to-pdf.html }
//Get Help From:-// http://july-code.blogspot.com/2008/06/export-gridview-to-pdf.html//http://www.pdftron.com/net/usermanual.html

42 unique visitors

How to take backup of a SQL Server Database Data

How to take backup of a SQL Server Database Data: -

1) Database (right click) -> Tasks -> Backup -> Database -> OK

(the database backup will be done)

42 unique users

2008/07/01

Import to Gridview from Excel Sheet (xlsx)

To import from an xlsx file to a Gridview, the whole code will be same as the post before, but the connection string should be changed.
It should be made: -


OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" +
Server.MapPath("~/App_Data/Running.xlsx") + ";" + "Extended Properties=\"Excel 12.0;HDR=Yes\"");

Rest is same.
The code will run properly.

Now the challenge is to select the path of the file at runtime.

38 visitors

Import to Gridview from Excel Sheet (xls)

Step 1 – Create Excel worksheet
1) Open Microsoft Excel and create a new Worksheet.
2) The sample data is as follows: - (any sample data)
We will keep the default name for the Worksheet (Sheet1).
3) Let us name and save the excel file as Running.xls.
Note: You can download the Excel file along with the code files from the Downloads section at the end of this article.


Step 2 –Display Excel Data using GridView Control
1) Start Visual Studio 2005.
2) Select Create Website and choose the Template ASP.NET Web Site. We can choose the language as C#/VB. Set the name for the project as ExcelGV.
3) Add the existing Excel file (Running.xls) that we created to the App_data folder.
4) Add a new .aspx file. Choose language C#/VB and, depending on the language, we will set the appropriate names: ExcelGVCS.aspx for C# or ExcelGVVB for VB.NET.
4) Drag and drop the GridView control on the .aspx page.
5) We will add the following statement in code behind above the namespace section.

-----------------------------------------------------------------------------------
using System.Data.OleDb;
------------------------------
protected void Page_Load(object sender, EventArgs e)
{
OleDbConnection DBConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath("~/App_Data/Running.xls") + ";" + "Extended Properties=\"Excel 8.0;HDR=Yes\"");
DBConnection.Open();
string SQLString = "SELECT * FROM [Sheet1$]";
OleDbCommand DBCommand = new OleDbCommand(SQLString, DBConnection);
IDataReader DBReader = DBCommand.ExecuteReader();
GridView1.DataSource = DBReader;
GridView1.DataBind();
DBReader.Close();
DBConnection.Close();
}
-----------------------------------------------------------------------------------
38 visitors

2008/06/30

Code for Export data from GridView to Excel: -

Code for Export data from GridView to Excel: -
--------------------------------------------------------------Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename=FileName.xls"); Response.Charset = ""; Response.ContentType = "application/vnd.xls";
StringWriter stringWrite = new StringWriter(); HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); try { dgdManageCategory.RenderControl(htmlWrite); } catch (Exception ex) { string s = ex.Message; Response.Write("Cannot Export to Excel"); }
Response.Write(stringWrite.ToString()); Response.End(); }
--------------------------------------------------------------
As I tried to Export data from GridView to Excel I got this error: -
Control 'dgdManageCategory' of type 'GridView' must be placed inside a form tag with runat=server.
So I searched the net on various sites and saw that I shouild add an overridden method that would solve the problem: -
So I used the method: -
--------------------------------------------------------------
public override void VerifyRenderingInServerForm(Control control) { // Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time. }
--------------------------------------------------------------
But I still got an error: -
"RegisterForEventValidation can only be called during Render();"
So I again searched the net and got this solution: -
Under the tag
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ManageCategory.aspx.cs" Inherits="CartTest.ManageCategory" %>
I should add "EnableEventValidation = "false" " to the above tag and thus the problem was solved.

Sites from where I got the help was: -
1) http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=118285
2) http://gridviewguy.com/ArticleDetails.aspx?articleID=182
3) http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html
--
4) http://geekswithblogs.net/azamsharp/archive/2005/12/21/63845.aspx

2008/06/26

Can AJAX be implemented in Windows Application?

Well technically you can use it in a windows application....

The long way to implement AJAX in a windows application.

just not in the way you may of intended. Since ajax is essentially asynchronous javascript and xml, you would need to use some sort of javascript engine (mozilla has a good one called SpiderMonkey which is written in c) and an XML parser, MSDOM or any standard lib would do. Create a class that implements the functionaly similar to a .NET 2.0 HttpRequest ( especially its asynchronous features ) and then export that class as a custom object so that it can be accessed by the javascript engine, being sure to implement the standard exception and errors found in regular XmlHttp calls. Once all of this is written you can write a windows application that loads a javascript file from anywhere, processes it (Either synchronously, or asynchronously) and returns the results so you can handle it appropriately.

The short way to implement AJAX in a windows application.

Quite simply, don't. The biggest feature of Ajax is that it simulates many windows applicsations ability to provide data on demand with out any postbacks or whatever. You can tweak your windows application to go above and beyond what Ajax could do by researching multithreading and the WinForms API and learning how to stream data from its source and automatically propagate that to the UI with out causing a noticeable wait to the main ui thread. But thats more into data visualization & web 2.0 centric than AJAX in itself.

2008/06/23

GridView to Excel Sheet

Excel Sheet to GridView: -
Write this code in button click event: -
-------------------------------------------------------------------------------------
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
myDataGrid.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
-------------------------------------------------------------------------------------

2008/06/13

Create a Local Version of the SQL Server Database

Qs) How to create a local version of the database if security permissions do not allow to copy a database in a sql server?

Ans) In this procedure the data will no be copied. Follow the steps: -
1) Right click on the Database name at server
2) Tasks
3) Generate Scripts
4) Follow the "SQL Server Script Wizard" steps, step by step as required.
(A script will be generated)
5) Execute this script generated by copying it on a query window in a local sql server.
(All the tables, stored procedures & scripts will be created without the data inside it)

2008/05/22

Add Data to the DataTable (in earlier post)

public void addDataToDataTable()
{
FreshCart fc = new FreshCart();
DataSet ds = new DataSet();
ViewState["ProdID"] = Request.QueryString["ProductID"];
ds = fc.GetProductDetailsByProductID(Convert.ToInt32(ViewState["ProdID"]));
System.Data.DataTable table = new DataTable("ManageShoppingCartTable");
table = (DataTable)(Session["DataTableHolder"]);
DataRow row;
row = table.NewRow();
row["ProductID"] = Convert.ToInt32(ds.Tables[0].Rows[0][("ProductID")]);
row["ProductName"] = ds.Tables[0].Rows[0][("ProductName")].ToString().Trim();
//if (table.Rows.Count < 1)
//{
row["Quantity"] = 1;
//}
//else if (table.Rows.Count >= 1)
//{
// row["Quantity"] = Convert.ToInt32(gvManageShoppingCart.FindControl("txtQuantity.Text"));
//}
row["Price"] = Convert.ToDouble(ds.Tables[0].Rows[0][("Price")].ToString().Trim());
row["NetPrice"] = Convert.ToInt32(row["Quantity"].ToString()) * Convert.ToDouble(row["Price"]);
//row["NetPrice"] = 2*Convert.ToDouble(row["Price"]);
//int s = 0;
int rowVal = Convert.ToInt32(row["ProductID"]);
bool blnIsProductExist = false;
// if current product id is already present then dont insert the row.
if (Convert.ToInt32(table.Rows.Count) == 0)
{
table.Rows.Add(row);
}
else
{
for (int i = 0; i < table.Rows.Count; i++)
{
//int rowVal = Convert.ToInt32(row["ProductID"]);
if (Convert.ToInt32(table.Rows[i][0]) == rowVal)
{
//s = s + 1;
blnIsProductExist = true;
}
else
{
//s = 0;
}
}


if (!blnIsProductExist)
{
lblMessageUpdate.Visible = false;
table.Rows.Add(row);
}

else
{
lblMessageUpdate.Visible = true;
lblMessageUpdate.Text = "The data is already present and cannot be updated".ToString();
}
}
lblFlag.Text = "1"; //set the flag to avoid postback after populating the gridview
Session["DataTableHolder"] = table;
gvManageShoppingCart.DataSource = ((DataTable)table).DefaultView;
gvManageShoppingCart.DataBind();
}

Create a DataTable


public void createSecondDataTable()
{
// Create a new DataTable.
System.Data.DataTable table = new DataTable("UpdatedManageShoppingCartTable");
// Declare variables for DataColumn and DataRow objects.
DataColumn column;


//Add 1st Column
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "ProductID";
//column.ReadOnly = true;
column.Unique = true;
//Add Column to table
table.Columns.Add(column);


//Add 2nd Column
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "ProductName";
//column.ReadOnly = true;
column.Unique = false;
//Add Column to table
table.Columns.Add(column);


//Add 3rd Column
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "Quantity";
//column.ReadOnly = true;
column.Unique = false;
//Add Column to table
table.Columns.Add(column);


//Add 4th Column
column = new DataColumn();
column.DataType = System.Type.GetType("System.Double");
column.ColumnName = "Price";
//column.ReadOnly = true;
column.Unique = false;
//Add Column to table
table.Columns.Add(column);


//Add 5th Column
column = new DataColumn();
column.DataType = System.Type.GetType("System.Double");
column.ColumnName = "NetPrice";
//column.ReadOnly = true;
column.Unique = false;


//Add Column to table
table.Columns.Add(column);

//Make the ProductID column the primary column
DataColumn[] PrimaryKeyColumns = new DataColumn[1];
PrimaryKeyColumns[0] = table.Columns["ProductID"];
table.PrimaryKey = PrimaryKeyColumns;


//Instantiate the dataset
//DataSet dataset = new DataSet();
//Add datatable to the dataset
//dataset.Tables.Add(table);
Session["UpdatedManageShoppingCartTableHolder"] = table;
}

2008/05/08

THIS DATASOURCE DOES NOT SUPPORT SERVER-SIDE DATA PAGING

To solve this problem (THIS DATASOURCE DOES NOT SUPPORT SERVER-SIDE DATA PAGING ), you must set GridView DataSource Property as DataSet not DataReader .

2008/05/07

An Example of Column Sorting

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
namespace CartTest
{
public partial class RevenueReport : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
lblGrandTotal.Visible = false;
}
}
public void populateGridView()
{
FreshCart fc = new FreshCart();
fc.RevenueReportFromDate = Convert.ToDateTime(txtFromDate.Text.Trim());
fc.RevenueReportToDate = Convert.ToDateTime(txtToDate.Text.Trim());
DataSet ds = new DataSet();
ds = fc.populategvRevenueReport();
ViewState["SortExpression"] = "OrderDate";
ViewState["SortDirection"] = "DESC";
// check whether the date is present or not
string returnValue;
returnValue = ds.Tables[0].Rows[0][("ReturnValue")].ToString().Trim();
if (returnValue == "0")
{
//no matching date
gvRevenueReport.Visible = false;
lblGrandTotal.Visible = false;
lblQtyTotal.Visible = false;
lblRevenueTotal.Visible = false;
lblMessage.Visible = true;
lblMessage.Text = "No Matching Date";
}
else if (returnValue == "1")
{
lblMessage.Visible = false;
gvRevenueReport.Visible = true;
gvRevenueReport.DataSource = ds.Tables[1].DefaultView;
ViewState["DataSource"] = ds.Tables[1];
lblGrandTotal.Visible = true;
lblQtyTotal.Visible = true;
lblQtyTotal.Text = ds.Tables[2].Rows[0][("Qty_Total")].ToString().Trim();
lblRevenueTotal.Visible = true;
lblRevenueTotal.Text = ds.Tables[3].Rows[0][("Revenue_Total")].ToString().Trim();
gvRevenueReport.DataBind();
PopulateDetails(ViewState["SortExpression"].ToString(), ViewState["SortDirection"].ToString());
}
}
protected void btnGo_Click(object sender, EventArgs e)
{
populateGridView();
}
public void PopulateDetails(string strSortExp, string strSortDir)
{
DataView dv = ((DataTable)ViewState["DataSource"]).DefaultView;
DataTable NewsTable = dv.ToTable();
DataView NewsView = NewsTable.DefaultView;
if (NewsView != null)
{
NewsView.Sort = strSortExp + " " + strSortDir;
gvRevenueReport.DataSource = NewsView;
gvRevenueReport.DataBind();
}
}
protected void gvRevenueReport_Sorting(object sender, GridViewSortEventArgs e)
{
string SortExpression = e.SortExpression;
ViewState["SortExpression"] = SortExpression;
if (ViewState["SortDirection"].ToString() == "DESC")
{
ViewState["SortDirection"] = "ASC";
}
else
{
ViewState["SortDirection"] = "DESC";
}
PopulateDetails(ViewState["SortExpression"].ToString(), ViewState["SortDirection"].ToString());
}
}
}

Some Tough Abbreviations

MIME - Multipurpose Internet Mail Extensions

2008/03/04

Convert from String to Float in C#

There are 2 ways: -

1) String to Double to Float (indirectly)
fc.Price = (float)Convert.ToDouble(txtPrice.Text);

2) String to Float (directly)
fc.Price = float.Parse(txtPrice.Text);

2008/02/21

The GridView 'gvManageProducts' fired event RowDeleting which wasn't handled.

To solve this exception do these:-

protected void gvManageProducts_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//required -do not remove
}

and also write this:-

protected void gvManageProducts_SelectedIndexChanged(object sender, EventArgs e)
{
//required -do not remove
}

2008/02/20

Pass a String (List) to a Stored Procedure and Update

ALTER PROCEDURE [dbo].[sprocUpdateStatusInProductMaster]
@List nvarchar(4000) -- value assigned to @List from DataLayer
AS
BEGIN
declare @ProdId2 int;
declare @Status2 nvarchar(100);
declare @CountRows int;
mailto:declare@val int;
declare @i int;
set @i = 1;
-- format of @List is @List = {1,True;2,False;3,True;4,False;5,False;}
-- execute sprocUpdateStatusInProductMaster ';1,True;2,False;3,True;4,False;5,False;'
set @List = ltrim(rtrim(Substring(@List,CharIndex(';',@List)+1,Len(@List)))); -- to eliminate the first semicolon ;
while(len(@List)>0)
BEGIN
set @ProdId2 = ltrim(rtrim(Substring(@List,1,CharIndex(',',@List)-1)));
set @List = ltrim(rtrim(Substring(@List,len(@ProdId2)+2,len(@List))));
set @Status2 = ltrim(rtrim(Substring(@List,1,CharIndex(';',@List)-1)));
set @List = ltrim(rtrim(Substring(@List,len(@Status2)+2,len(@List))));

update tblProductMaster set IsActive = @Status2
where ProductID = @ProdId2;
END
END

Label to Integer

Label lbl = (Label)gvManageProducts.Rows[i].FindControl("lblProductId");
int lblint = Int32.Parse(lbl.Text);

2008/01/11

To send two values from one page to another

Response.Redirect("AddEditQuestion.aspx QuestionId=" + intQuestionId + "&QuizId=" + ViewState["QuizId"]);

Checkbox in to a boolean variable

bool isactive;
if (chkCategoryActive.Checked)
{
fc.IsActive = true;
}
else
{
fc.IsActive = false;
}

or it can also be written as

fc.IsActive2 = Convert.ToBoolean(chkActive.Checked);

2008/01/10

Another Typical GridView

Take the code below and replace ( by < and ) by > in MsWord.


(%--(asp:GridView ID="dgdManageCategory" runat="server" AutoGenerateColumns="false" OnRowCommand="dgdManageCategory_RowCommand" OnRowDeleting="dgdManageCategory_RowDeleting" OnRowEditing="dgdManageCategory_RowEditing")
(Columns)

(asp:TemplateField HeaderText="CategoryID" Visible="false")
(ItemTemplate)
(asp:Label ID="lblCatID" runat="server" Text='(%# Eval("CategoryID")%)' /)
(/ItemTemplate)
(/asp:TemplateField)

(asp:TemplateField HeaderText="Status")
(ItemTemplate)
(asp:CheckBox ID="cbIsActive" runat="server" Checked='(%# Convert.ToBoolean(Eval("IsActive"))%)' /)
(/ItemTemplate)
(/asp:TemplateField)

(asp:BoundField DataField="CategoryName" HeaderText="Category Name" ConvertEmptyStringToNull="true" /)

(asp:TemplateField HeaderText="Edit")
(ItemTemplate)
(asp:Button ID="lbnEdit" runat="server" CommandArgument='(%# Eval("CategoryID")%)' CommandName="Edit" Text="Edit" /)
(/ItemTemplate)
(/asp:TemplateField)

(asp:TemplateField HeaderText="Delete")
(ItemTemplate)
(asp:Button ID="lbnDelete" runat="server" CommandArgument='(%# Eval("CategoryID")%)' CommandName="Delete" Text="Delete"
OnClientClick="JavaScript:return confirm('Are you sure you want to delete ');"/)
(/ItemTemplate)
(/asp:TemplateField)

(asp:TemplateField HeaderText="Products")
(ItemTemplate)
(asp:Button ID="lbnProducts" runat="server" CommandArgument='(%# Eval("CategoryID")%)' CommandName="Products" Text="Products" /)
(/ItemTemplate)
(/asp:TemplateField)

(/Columns)
(/asp:GridView)--%)

A Typical GridView

Take the code below and replace ( by < and ) by > in MsWord.

(asp:GridView ID="dgdManageUsers" runat="server" AutoGenerateColumns="False"
AllowPaging="true" PagerStyle-HorizontalAlign="Right" PagerSettings-Mode="Numeric" PagerSettings-PageButtonCount="3"
OnPageIndexChanging="dgdManageUsers_PageIndexChanging" EmptyDataText="No records found" OnRowDeleting="dgdManageUsers_RowDeleting"
OnRowCommand="dgdManageUsers_RowCommand" )

(Columns)
(asp:TemplateField HeaderText="CategoryID" Visible="False")
(ItemTemplate)
(asp:Label ID="lblUserID" runat="server" Text='(%# Eval("UserId")%)' /)
(/ItemTemplate)
(/asp:TemplateField)

(asp:BoundField HeaderText="Full Name" DataField="FullName" /)

(asp:BoundField HeaderText="Email" DataField="Email" /)

(asp:BoundField HeaderText="Registration Date" DataField="RegistrationDate" /)

(asp:TemplateField HeaderText="Edit")
(ItemTemplate)
(asp:Button runat="server" ID="btnEdit" CommandName="Edit" CommandArgument='(%# Eval("UserId")%)' Text="Edit"/)
(/ItemTemplate)
(/asp:TemplateField)

(asp:TemplateField HeaderText="Delete")
(ItemTemplate)
(asp:Button runat="server" ID="btnDelete" CommandName="Delete" CommandArgument='(%# Eval("UserId")%)' Text="Delete"
OnClientClick="JavaScript:return confirm('Are you sure you want to delete ');" /)
(/ItemTemplate)
(/asp:TemplateField)

(asp:TemplateField)
(ItemTemplate)
(asp:TextBox runat="server" ID="txtEditBox" Visible="False" Text='(%# DataBinder.Eval(Container.DataItem,"Email") %)' /)
(/ItemTemplate)
(/asp:TemplateField)
(/Columns)
(PagerSettings PageButtonCount="3" /)
(PagerStyle HorizontalAlign="Right" /)

(/asp:GridView)

2008/01/08

if ( ! Page.IsPostBack)

if (!Page.IsPostBack)
{
populateUserDetailsGrid();
}

-> Working with any kind of WebForm is posting data back to the server to enable data and command processing. The populateUserDetailsGrid() method is fired when this above condition is not true.

2008/01/07

The GridView 'gdABCD' fired event PageIndexChanging which wasn't handled.

1) If we change DataGrid to a GridView so inside any Event we change
DataGridPageChangedEventArgs to GridViewPageEventArgs.

2) If you set AllowPaging="true" or AllowSorting="true" on a GridView control without using a DataSourceControl DataSource (i.e. SqlDataSource, ObjectDataSource), you will run into the following errors: -

When changing the page on the GridView control: -

The GridView 'GridViewID' fired event PageIndexChanging which wasn't handled.
When clicking a column name to sort the column on the GridView control: -

The GridView 'GridViewID' fired event Sorting which wasn't handled.

As a result of not setting the DataSourceID property of the GridView to a DataSourceControl DataSource, you have to add event handlers for sorting and paging.

GridView PageIndex Code Behind

protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridView.PageIndex = e.NewPageIndex;
gridView.DataBind();
}

Paging concepts in GridView

The DataGrid control requires additional coding for paging. The GridView control automatically supports paging by setting the PagerSettings property. The PagerSettings property supports four modes: Numeric ( default ), NextPrevious, NumericFirstLast, and NextPreviousFirstLast.

The Numeric mode displays numbered page links instead of "next/prev" links, and the NumericFirstLast option adds first and last page links. The GridView control's PagerStyle property can be used to set styles and the position of the pager.
Additionally, you can customize the pager buttons for the GridView control using a PagerTemplate.


Custom paging support in the GridView is supplied by the bound data source control as opposed to the AllowCustomPaging mechanism supplied by the DataGrid control.

2008/01/04

Get Row Index with Gridview Select Button

When you autoGenerate a Select button with a Gridview, to find the RowIndex for that particular row, you can use the SelectedIndexChanged Event.

Inside that event, try something like this (with a label called 'Label1':

Dim row As GridViewRow = MyGridView.SelectedRow
Dim intRow as Integer=Row.RowIndex
label1.text=intRow.ToString

or


GridViewRow gvr = new GridViewRow();
gvr = dgdManageUsers.SelectedIndex;
int introw = gvr.RowIndex;
label1.text=intRow.ToString;

Some CSS Examples

body {
background: #FFFFFF;
color: #000000;
margin: 0;
padding: 0;
}
p {
font-family: Arial;
font-size: 12px;
}
h1 {
font-family: Arial;
font-size: 14px;
color: #000000;
}
a:link {
font-family: Arial;
font-size: 12px;
color: #000000;
}
a:hover {
font-family: Arial;
font-size: 12px;
color: #FF0000;
}
.textbox {
font-family: Arial;
font-size: 12px;
border: 1px solid black;
}
.button {
font-family: Arial;
border: 1px solid black;
background-color: #CCCCCC;
}
.dropdownmenu {
font-family: Arial;
font-size: 12px;
background-color: #CCCCCC;
}

ItemStyle/HeaderStyle Properties not working with DataGrid

Remember that a DataGrid generates an HTML Table, with TableRows and Cells. If you have ItemStyle/HeaderStyle/SelectedItem/FooterStyle tags with display properties (like forecolor/bold/font properties) and some of them are not displaying like you think they should, be sure to check your page for a StyleSheet.

If you have a TD tag section in your page's stylesheet - -whatever properties you set there will normally override whatever you add into your DataGrid's Item styles.

Drop Down List

1. http://www.janetsystems.co.uk/Articles/NetArticles/tabid/74/itemid/161/modid/449/Default.aspx