Pages

Sunday, March 20, 2011

FckEditor

0 comments

--------------------------------------------------------
FCKEditor Sample

Saturday, March 19, 2011

Alphabetic Paging Gridview

0 comments

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


protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ShowAllProjects();
}

}

public void ShowAllProjects()
{
DataTable dt = new DataTable();
dt = NSBuilder.DataAccess.GetDataSet("Usp_BindCategory_ForSortingTest").Tables[0];
if (dt.Rows.Count > 0)
{
gridAllProjects.Visible = true;
gridAllProjects.DataSource = dt;
gridAllProjects.DataBind();

}
else
{
gridAllProjects.Dispose();
gridAllProjects.Visible = false;

}
}


protected void gridAllProjects_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
TableCell tc = new TableCell();
TableCell tc1 = new TableCell();

tc.Text = "[Page:";
tc1.Text = "]";
Table tbl = new Table();
tbl = (Table)(e.Row.Cells[0].Controls[0]);
tbl.Rows[0].Cells.AddAt(gridAllProjects.PageIndex, tc);
tbl.Rows[0].Cells.AddAt(gridAllProjects.PageIndex + 2, tc1);
}
}

protected void gridAllProjects_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
TableCell cell = e.Row.Cells[0];

cell.ColumnSpan = 2;

for (int i = 65; i <= (65 + 25); i++)
{

LinkButton lb = new LinkButton();

lb.Text = Char.ConvertFromUtf32(i) + " ";

lb.CommandArgument = Char.ConvertFromUtf32(i);

lb.CommandName = "AlphaPaging";

cell.Controls.Add(lb);

lb.ToolTip = "Click to find the categories starting with :- " + lb.Text;
// lb.BackColor = System.Drawing.ColorTranslator.FromHtml("#6b8ade");
lb.CssClass = "simple";
// lb.Attributes.Add("onmouseover","style='backbol
// lb.Style.Add("background-color", "red");

if (! CheckCategoryExistsOrNot(lb.Text))
{
lb.Visible = false;
}

}
}
}

public bool CheckCategoryExistsOrNot(string s)
{
DataTable dt = new DataTable();
Hashtable ht = new Hashtable();
ht.Add("@C", s);

string result;
bool r;
result = Convert.ToString(NSBuilder.DataAccess.ExecuteNonQueryWithReturnParameter
("Usp_CheckCategorEXITSOrNOTForSortingTest",ht));

if (result == "1")
{
r = true;
}
else
{
r= false;
}
return r;

}


protected void gridAllProjects_RowCommand(object sender, GridViewCommandEventArgs e)
{
DataTable dt = new DataTable();
Hashtable ht = new Hashtable();
if (e.CommandName.Equals("AlphaPaging"))
{
ht.Add("@C", e.CommandArgument.ToString());
dt = NSBuilder.DataAccess.GetDataSet("Usp_BindCategory_ForSortingTest", ht).Tables[0];
gridAllProjects.DataSource = dt;
gridAllProjects.DataBind();
}


}


protected void gridAllProjects_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridAllProjects.PageIndex = e.NewPageIndex;
ShowAllProjects();
}

}

---------------stored proc-----
alter PROCEDURE [dbo].[Usp_CheckCategorEXITSOrNOTForSortingTest]
(
@C Char(1) = null

) -- Usp_CheckCategorEXITSOrNOTForSortingTest 'A'
AS


BEGIN
DECLARE @VAR INT

IF EXISTS (SELECT CATEGORY FROM tbl_Category WHERE Category LIKE @C + '%')

SET @VAR = 1
ELSE
SET @VAR = -1

END
--PRINT @VAR
RETURN @VAR




------css class----

.simple
{
background-color:#bd0000;
color:#ffffff;
}
.simple:hover
{
background-color:#ffffff;
color:#bd0000;
}
--------------------

Saturday, March 5, 2011

UsefulLinks

0 comments

BLOGS

0. aspdotnet-suresh.blogspot.com
1. CsharpdotNetFreak
2. (Ramani sandeep)
3. SQL-Madhiwan
4..NetTips-Abhijeet Jana
5. www.abhisheksur.com
6. codesforprogrammers.blogspot.com
7. aspalliance
8. megasolutions.net
9. DotnetFreaks
10. AspnetTutorials
11. AspSnippets.com
12. T-SQL Format
13.CodeFormat for Blogs
14. EggHeadcafe FAQ
15.TechTasks Bloging

16. www.ezzylearning.com

Thursday, February 10, 2011

Dropdownlist 2 Column display

0 comments

Displaying two columns in dropdownlist----------------------------------

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
bindDropDown();
}

}

public void bindDropDown()
{


//string[,] arr_Place = {
// {"Delhi","India"},
// {"Newyork","America"},
// {"Taiwan","China"},
// {"Colombo","Srilanka"},
// {"Lahore","Pakistan"},

// };

DataSet dsdata = new DataSet();
dsdata = GetData();
int rowcount = Convert.ToInt32(dsdata.Tables[0].Rows.Count);
int colcount = 2;

string [,] arr_Place = new String[rowcount,colcount];

string a = String.Empty;
string b = String.Empty;

// FILL THE ARRAY WITH THE DATA
for (int i = 0; i < dsdata.Tables[0].Rows.Count; i++)
{
a = dsdata.Tables[0].Rows[i][0].ToString();
b = dsdata.Tables[0].Rows[i][1].ToString();

arr_Place[i, 0] = a;
arr_Place[i, 1] = b;

}



// NOW AFTER FILLING , BIND THE ARRARY WITH THE DROPDOWNLIST

string str = String.Empty;

for (int i = 0; i < arr_Place.GetLength(0); i++)
{

str = arr_Place[i, 0].ToString() + " ---> " + arr_Place[i, 1].ToString();

DropDownList1.Items.Add(str);
// DropDownList1.Items.Add(new ListItem(arr_Place[i, 0], arr_Place[i, 1]));
}

DropDownList1.Items.Insert(0, "--select one--");

}



public DataSet GetData()
{
// [Usp_checkCountyAvailable_Test]
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["cn"].ConnectionString.ToString();

SqlDataAdapter adp = new SqlDataAdapter("Usp_checkCountyAvailable_TEst", con);
adp.Fill(ds);
return ds;
}

Saturday, December 18, 2010

Fileupload with file type check

0 comments

--------------------------------------
protected void btnUpload_Click(object sender, EventArgs e)
{
string path = Server.MapPath("upload/");
bool boolOk = false;

if (FUpload.HasFile)
{
string ext = String.Empty;
ext = System.IO.Path.GetExtension(FUpload.FileName).ToLower();

String[] allowed = { ".doc", ".pdf", ".txt" };
for (int i = 0; i <= allowed.Length - 1; i++)
{
if (ext == allowed[i])
{
boolOk = true;
}
if (boolOk == true)
{
try
{
FUpload.PostedFile.SaveAs(path + FUpload.FileName);
lblmsg.Text = "File uploaded successfully!!";
}
catch (Exception ex)
{
lblmsg.Text = ex.Message.ToString();
}

}
else
{
lblmsg.Text = "Only text files are supported. Please change!!";
}

}

Thursday, December 16, 2010

To delete all the TABLES, SPs, TRIGGERS, VIEWS from a Database

0 comments

JUST RUN THIS QUERY ON THE SELECTED DATABASE
-----------------------------------------------------




DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 ORDER BY [name])

WHILE @name is not null
BEGIN
SELECT @SQL = 'DROP PROCEDURE [dbo].[' + RTRIM(@name) +']'
EXEC (@SQL)
PRINT 'Dropped Procedure: ' + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

/* Drop all views */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
SELECT @SQL = 'DROP VIEW [dbo].[' + RTRIM(@name) +']'
EXEC (@SQL)
PRINT 'Dropped View: ' + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

/* Drop all functions */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
SELECT @SQL = 'DROP FUNCTION [dbo].[' + RTRIM(@name) +']'
EXEC (@SQL)
PRINT 'Dropped Function: ' + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

/* Drop all Foreign Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)

WHILE @name is not null
BEGIN
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
WHILE @constraint IS NOT NULL
BEGIN
SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT ' + RTRIM(@constraint)
EXEC (@SQL)
PRINT 'Dropped FK Constraint: ' + @constraint + ' on ' + @name
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
END
GO

/* Drop all Primary Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)

WHILE @name IS NOT NULL
BEGIN
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
WHILE @constraint is not null
BEGIN
SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT ' + RTRIM(@constraint)
EXEC (@SQL)
PRINT 'Dropped PK Constraint: ' + @constraint + ' on ' + @name
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
END
GO

/* Drop all tables */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
SELECT @SQL = 'DROP TABLE [dbo].[' + RTRIM(@name) +']'
EXEC (@SQL)
PRINT 'Dropped Table: ' + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO



Sunday, December 5, 2010

Handling Dropdown list inside Gridview with Autopostback

0 comments

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



Many a times there are circumstances where by we need to use dropdown list inside a Gridview and also handle the index changed event of the dropdown list. The easy example of this kind of requirement would be when we nee to fill another dropdown list in the same row from the value selected in the first dropdown list.

We all know that the dropdown list does not support command name property so you cannot handle the event in the row command event.
A simple solution to the problem is to use the namingcontainer in the selectedindexchanged event and get the reference of the parent row view. After that we can do what we want from the row view. Here is an example in the code.
protected void dropdownlist1_SelectedIndexChanged(object sender, EventArgs e) {
// get reference to the row
GridViewRow gvr = (GridViewRow)(((Control)sender).NamingContainer);
// Get the reference of this DropDownlist
DropDownList dropdownlist1 = (DropDownList) gvr.FindControl("dropdownlist1");
// Get the reference of other DropDownlist in the same row.
DropDownList ddlParagraph = (DropDownList) gvr.FindControl("ddlParagraph");
}



GridView1_SelectedIndexChanged_1

0 comments

SelectedIndexChanged
---------------------------------------------------------




protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = GridView1.SelectedRow.Cells[0].Text;
TextBox2.Text = GridView1.SelectedRow.Cells[1].Text;
TextBox3.Text = GridView1.SelectedRow.Cells[2].Text;
TextBox4.Text = GridView1.SelectedRow.Cells[3].Text;
}





Saturday, November 27, 2010

Dropdown list inside Gridview with Autopostback

0 comments

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





Many a times there are circumstances where by we need to use dropdown list inside a Gridview and also handle the index changed event of the dropdown list. The easy example of this kind of requirement would be when we nee to fill another dropdown list in the same row from the value selected in the first dropdown list.

We all know that the dropdown list does not support command name property so you cannot handle the event in the row command event.
A simple solution to the problem is to use the namingcontainer in the selectedindexchanged event and get the reference of the parent row view. After that we can do what we want from the row view.

Here is an example in the code.

protected void dropdownlist1_SelectedIndexChanged(object sender, EventArgs e)
{
// get reference to the row
GridViewRow gvr = (GridViewRow)(((Control)sender).NamingContainer);

// Get the reference of this DropDownlist
DropDownList dropdownlist1 = (DropDownList) gvr.FindControl("dropdownlist1");


// Get the reference of other DropDownlist in the same row.
DropDownList ddlParagraph = (DropDownList) gvr.FindControl("ddlParagraph");
}





With BoundColumns

0 comments

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




//WITH BOUND COLUMNS
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
// ValidateRequest=&quot;false&quot; in the page directive
// GridViewRow selectedRow = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;

if (e.CommandName.ToLower().Equals(&quot;select&quot;))
{
GridViewRow grow = (GridViewRow)((Button)e.CommandSource).NamingContainer;

int index = Convert.ToInt32(grow.RowIndex);

DropDownList myddl = (DropDownList)(grow.FindControl(&quot;ddlCountry&quot;));

TextBox1.Text = grow.Cells[1].Text;
TextBox2.Text = grow.Cells[2].Text;
TextBox3.Text = grow.Cells[3].Text;
TextBox4.Text = grow.Cells[4].Text;
TextBox5.Text = myddl.SelectedItem.Text;
}
}






Row_Command_2

0 comments

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




<ItemTemplate>
<asp:LinkButton ID="lnkview" runat="server" CommandName="ViewFranchisee" CommandArgument='<%#Eval("Email") %>'
CssClass="tahomatext"><img src="../images/icon_details.png" style="border:0;" alt="Franchisee Details" title="Franchisee Details" /></asp:LinkButton>
</ItemTemplate>

protected void grdFranch_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToString() == "ViewFranchisee")
{
email = e.CommandArgument.ToString();
Response.Redirect("ViewFranchiseeProfile.aspx?email=" + email);
}
}





Row_Command_Edit_Update

0 comments

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




<ItemTemplate>
<asp:Label ID="lblluserName" runat="server"
Text='<%#Eval("LastName")+","+Eval("FirstName") %> '></asp:Label>
</ItemTemplate>


<ItemTemplate>
<asp:Label ID="lblStatusTerritory" Text='<%#get(Convert.ToBoolean((Eval("IsActive"))))%>'
runat="server"></asp:Label>
</ItemTemplate>



<asp:TemplateField ItemStyle-Width="40px">
<ItemTemplate>
<asp:ImageButton ID="btnEdit" CommandName="Edit" ImageUrl="~/images/edit1.png" ToolTip="Edit record. "
runat="server" Height="15" Width="15" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnupdate" runat="server" CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="btncancel" runat="server" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>

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

protected void grdDirectory_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToString().Equals("Update"))
{
DataTable dt = new DataTable();
Hashtable ht = new Hashtable();

LinkButton lnkupdate = (LinkButton)e.CommandSource;
GridViewRow grow = lnkupdate.NamingContainer as GridViewRow;

TextBox txtworkphone = (TextBox)grow.FindControl("txtworkphone");
string strWorkPhone = txtworkphone.Text.ToString().Trim(); ******

Label lblID = (Label)grow.FindControl("lblID");

TextBox txtCompany = (TextBox)grow.FindControl("txtCompany");
string strCompany = txtCompany.Text.ToString().Trim();
}
}

if (e.CommandName.ToString().Equals("Delete"))
{
DataTable dt = new DataTable();
Hashtable ht = new Hashtable();

//LinkButton lnkDelete = (LinkButton)e.CommandSource;
ImageButton imgDelete = (ImageButton)e.CommandSource;
GridViewRow grow = imgDelete.NamingContainer as GridViewRow;

// TextBox txtworkphone = (TextBox)grow.FindControl("txtworkphone");
Label lblID = (Label)grow.FindControl("lblID");

ht.Add("@id", lblID.Text);








0 comments

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



protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int index = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "UnitPrice"));

if (index <= 30)
{
// e.Row.ForeColor = System.Drawing.Color.Red; // whole row will be red
e.Row.Cells[4].ForeColor = System.Drawing.Color.Red; // only the unitprice cell will be red.
}
}
else
{

}
}




DropdownList in ItemTemplate having the item preselected

0 comments

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


############################################################

<asp:GridView ID="grdData" DataKeyNames="userid,categoryname">


protected void grdData_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList _ddlcategory = (DropDownList)e.Row.FindControl("ddlcategory");
if (_ddlcategory != null)
{
_ddlcategory.DataSource = GetCategory();
_ddlcategory.DataTextField = "categoryname";
_ddlcategory.DataValueField = "categoryname";
_ddlcategory.DataBind();

_ddlcategory.SelectedItem.Text = grdData.DataKeys[e.Row.RowIndex].Values[1].ToString();


}

}

}



public DataTable GetCategory()
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["conPractice"].ToString();

SqlDataAdapter adp = new SqlDataAdapter("GetCategory", con);
adp.Fill(dt);

return dt;

}

############################################


Pager row format [ ]

0 comments

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


1.



protected void grdProject_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
TableCell tc = new TableCell();
TableCell tc1 = new TableCell();

tc.Text = "[Page:";
tc1.Text = "]";
Table tbl = new Table();
tbl = (Table)(e.Row.Cells[0].Controls[0]);
tbl.Rows[0].Cells.AddAt(grdProject.PageIndex, tc);
tbl.Rows[0].Cells.AddAt(grdProject.PageIndex + 2,tc1);
}


}

##########################################################

2.


<asp:GridView ID="grid1" runat="server" AutoGenerateColumns="false"
DataKeyNames="ProductId,Category">


public void grid1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlCategory = (DropDownList)e.Row.FindControl("ddlCategory");
if (ddlCategory != null)
{
ddlCategory.DataSource = Product.FetchCategory();
ddlCategory.DataBind();
ddlCategory.SelectedValue =
grid1.DataKeys[e.Row.RowIndex].Values[1].ToString();

// using DatakeyNames property
}
}

if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList ddlCategoryInput = (DropDownList)e.Row.FindControl(
"ddlCategoryInput");
ddlCategoryInput.DataSource = Product.FetchCategory();
ddlCategoryInput.DataBind();
}
}



##########################################################



Total in Footer_Gridview

0 comments

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


1.



protected void GridView1_DataBound(object sender, EventArgs e)
{
decimal valueInStock = 0;
foreach (GridViewRow row in GridView1.Rows)
{
decimal price = Decimal.Parse(row.Cells[2].Text.Substring(1));
int unitsInStock = Int32.Parse(row.Cells[3].Text);
valueInStock += price * unitsInStock;
}

GridViewRow footer = GridView1.FooterRow;

footer.Cells[0].ColumnSpan = 3;
footer.Cells[0].HorizontalAlign = HorizontalAlign.Center;

footer.Cells.RemoveAt(2);
footer.Cells.RemoveAt(1);

footer.Cells[0].Text = "Total value in stock (on this page): " + valueInStock.ToString("C");

}

}






Format Gridview with OnRowCreated function

0 comments

----------------------------------------------------------------------------------
1

if (e.Row.RowType == DataControlRowType.DataRow)
{
Comments = (String)DataBinder.Eval(e.Row.DataItem, "Comment");
if (Comments.Length > 30)
{
Comments = Comments.Substring(0, 40) +"...";
e.Row.ForeColor = System.Drawing.Color.Crimson;
e.Row.Font.Italic = true;
}
}

---------------------------------------------------------------------------------
2
protected void grdData_RowCreated(object sender, GridViewRowEventArgs e)
{

if ((e.Row.RowType == DataControlRowType.DataRow) && (e.Row.RowState == DataControlRowState.Selected))
{
string strCellvalue = DataBinder.Eval(e.Row.DataItem, "categoryname").ToString();
if (strCellvalue == "Admin")
{
e.Row.BackColor = System.Drawing.Color.LightPink;
}
}
}

#######################################################
3

<asp:GridView runat="server" ID="gridProducts" DataSourceID="productsSource"
AutoGenerateColumns="false" OnRowCreated="gridProducts_RowCreated">
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="ProductNumber" HeaderText="Number" />
<asp:BoundField DataField="DaysToManufacture" HeaderText="Days To Manufacture" />
</Columns>
</asp:GridView>

protected void gridProducts_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int daysToManufacture = (int)DataBinder.Eval(e.Row.DataItem, "DaysToManufacture");

if (daysToManufacture == 0)
{
e.Row.BackColor = System.Drawing.Color.LightPink;
e.Row.ForeColor = System.Drawing.Color.Maroon;
}
else if (daysToManufacture == 1)
{
e.Row.BackColor = System.Drawing.Color.LightCyan;
e.Row.ForeColor = System.Drawing.Color.DarkBlue;
}
else
{
e.Row.BackColor = System.Drawing.Color.LightGray;
e.Row.ForeColor = System.Drawing.Color.Red;
}
}
}
####################################################


RowDeleting(1)

0 comments

---------------------------------------------------------------
1.
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
TableCell cell = GridView1.Rows[e.RowIndex].Cells[2];
if (cell.Text == "Chai")
{
e.Cancel = true;
// lblmsg.Text = "You cannot delete : Chai";
ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('You cannot delete this product.');</script>");
}
else
{
Response.Write(" Product Deleted"); // write here the code to delete the product.
}
}
###########################################









Thursday, November 25, 2010

Sorting Gridview

0 comments



if (!IsPostBack)
{
ViewState["sortOrder"] = "";
bindGridView("", "");
}

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

public void bindGridView(string sortExp,string sortDir)
{
DataSet myDataSet = new DataSet();
myDataSet = NSBuilder.DataAccess.GetDataSet("Usp_GetAllProjects");

DataView myDataView = new DataView();
myDataView = myDataSet.Tables[0].DefaultView;

if (sortExp!=string.Empty)
{
myDataView.Sort = string.Format("{0} {1}", sortExp, sortDir);
}

grdProjects.DataSource = myDataView;
grdProjects.DataBind();

}

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


public string sortOrder
{
get
{
if (ViewState["sortOrder"].ToString() == "desc")
{
ViewState["sortOrder"] = "asc";
}
else
{
ViewState["sortOrder"] = "desc";
}
return ViewState["sortOrder"].ToString();
}
set
{
ViewState["sortOrder"] = value;
}
}


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

protected void grdProjects_Sorting(object sender, GridViewSortEventArgs e)
{
bindGridView(e.SortExpression, sortOrder);
// sortorder property used here.
}

protected void grdProjects_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdProjects.PageIndex = e.NewPageIndex;
bindGridView("","");
}

----------




Sunday, November 21, 2010

Pre-Selecting DropDownlist in EditItemTemplate-Gridview

0 comments

PRE SELECTING ITEMS IN DROPDOWNLIST IN GRIDVIEW EDIT MODE
---------------
<asp:TemplateField HeaderText="State">
<ItemTemplate>
<asp:Label ID="lblState" runat="server" Text='<%#Eval("TState") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlState" CssClass="textTableElement" AutoPostBack="true"

ToolTip='<%#Container.DataItemIndex%>' runat="server"

OnSelectedIndexChanged="ddlState_SelectedIndexChanged"> </asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
******************************

protected void grdData_RowEditing(object sender, GridViewEditEventArgs e)
{
grdData.EditIndex = e.NewEditIndex;
BindGrid();

GridViewRow grow = (GridViewRow)grdData.Rows[e.NewEditIndex];

DropDownList ddl = new DropDownList();
ddl = (DropDownList)grow.FindControl("ddlCat");
ddl.DataSource = GetCategory();
ddl.DataTextField = "categoryname";
ddl.DataValueField = "categoryid";
ddl.DataBind();

string str = ViewState["cat"].ToString();

ddl.Items.FindByText(str).Selected = true;

}
--------------------------------------------

protected void grdData_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "edit")
{
GridViewRow grow = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
Int32 userid = Convert.ToInt32(e.CommandArgument.ToString());
ViewState["userid"] = userid;

Label lblCat = new Label();
lblCat = (Label)grow.FindControl("lblcategory");

ViewState["cat"] = lblCat.Text.ToString(); // used in row_editing event to preselect the previous item

}

//******************
if (e.CommandName == "update")
{
GridViewRow grow = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);

DropDownList ddl = (DropDownList)grow.FindControl("ddlCat");

ddl.DataSource = GetCategory(); // function returns a datatable
ddl.DataTextField = "categoryname";
ddl.DataValueField = "categoryid";
ddl.DataBind();

Int32 userid = Convert.ToInt32(ViewState["userid"]);
Int32 catid = Convert.ToInt32(ViewState["categoryid"]);
Int32 intresult;

SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["conPractice"].ToString();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UpdateUser";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;


SqlParameter param = new SqlParameter();

cmd.Parameters.AddWithValue("@userid", userid);
cmd.Parameters.AddWithValue("@categoryid", catid);
param = cmd.Parameters.Add("ReturnValue", SqlDbType.Int);
param.Direction = ParameterDirection.ReturnValue;


con.Open();
cmd.ExecuteNonQuery();

intresult =(int) cmd.Parameters["ReturnValue"].Value;
con.Close();

if (intresult == 1)
{
lblmsg.Text="Updated Successfully!";

grdData.EditIndex = -1;
BindGrid();
}
if (intresult == -1)
{
lblmsg.Text = "Not Updated!!";
}
}
//******************
if (e.CommandName == "delete")
{

GridViewRow grow = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
}
}

******************************

protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlState;
ddlState = (DropDownList)sender;

string state = ddlState.SelectedItem.Text;


ViewState["state"] = state;

DropDownList ddlCounty;
ddlCounty = (DropDownList)grdTerritory.Rows[Convert.ToInt32
(ddlState.ToolTip)].FindControl("ddlCounty");


clsBuilder.bind_County(ddlCounty, state);

}
**************************





 

CodeAddict.com | Copyright 2009 Tüm Haklar? Sakl?d?r | Free Blogger Templates by GoogleBoy Download Free Wordpress Templates. Unblock through unblock myspace proxy, Hillsongs by Guitar Song Chords