--------------------------------------
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!!";
}
}
Saturday, December 18, 2010
Fileupload with file type check
0 comments Saturday, December 18, 2010 Posted by Vikas SharmaLabels: FILE_UPLOAD, GeneralTips n Tricks
Thursday, December 16, 2010
To delete all the TABLES, SPs, TRIGGERS, VIEWS from a Database
0 comments Thursday, December 16, 2010 Posted by Vikas SharmaLabels: SQL_SPs, SQL_Utility_StoredProcs
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 Sunday, December 05, 2010 Posted by Vikas Sharma----------------------------------------------------
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 Sunday, December 05, 2010 Posted by Vikas SharmaLabels: GV_SelectedIndexChanged
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 Saturday, November 27, 2010 Posted by Vikas Sharma---------------------------------------------------------------------
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 Saturday, November 27, 2010 Posted by Vikas SharmaLabels: ROW_COMMAND
------------------------------------------------------------
//WITH BOUND COLUMNS
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
// ValidateRequest="false" in the page directive
// GridViewRow selectedRow = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;
if (e.CommandName.ToLower().Equals("select"))
{
GridViewRow grow = (GridViewRow)((Button)e.CommandSource).NamingContainer;
int index = Convert.ToInt32(grow.RowIndex);
DropDownList myddl = (DropDownList)(grow.FindControl("ddlCountry"));
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 Saturday, November 27, 2010 Posted by Vikas SharmaLabels: ROW_COMMAND
---------------------------------------------------------------
<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 Saturday, November 27, 2010 Posted by Vikas SharmaLabels: ROW_COMMAND
----------------------------------------------------------
<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);
Labels: ROW_DATABOUND
-------------------------------------------------------------------
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 Saturday, November 27, 2010 Posted by Vikas SharmaLabels: ROW_DATABOUND
-------------------------------------------------------------
############################################################
<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 Saturday, November 27, 2010 Posted by Vikas SharmaLabels: ROW_DATABOUND
---------------------------------------------------------------------------
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 Saturday, November 27, 2010 Posted by Vikas SharmaLabels: Gridview_DataBound
------------------------------------------------------------
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 Saturday, November 27, 2010 Posted by Vikas SharmaLabels: ROW_CREATED
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 Saturday, November 27, 2010 Posted by Vikas SharmaLabels: Row_Deleting
---------------------------------------------------------------
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 Thursday, November 25, 2010 Posted by Vikas SharmaLabels: GeneralTips n Tricks
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 Sunday, November 21, 2010 Posted by Vikas SharmaLabels: GeneralTips n Tricks
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);
}
**************************
Saturday, November 13, 2010
change status function
0 comments Saturday, November 13, 2010 Posted by Vikas SharmaLabels: Asp.net Utility Functions
----------------------------------------------------
<asp:TemplateField HeaderText="Change Status">
<ItemTemplate>
<asp:LinkButton ID="lnkbtnIsactive" runat="server"
OnClick="change_status"
CommandArgument='<%#Eval("ID")+","+Eval("ProjectID") %>'
ToolTip='<%#Eval("UserName")%>'
Text='<%#get(Convert.ToBoolean((Eval("IsActive"))))%>'
></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
public string get(bool act)
{
if (act == true)
{
return "Deactivate";
}
else
{
return "Activate";
}
}
protected void change_status(object sender, EventArgs e)
{
if (Convert.ToInt32(Session["AccessRight"]) == 1)
{
lnk = ((LinkButton)(sender));
string[] array = lnk.CommandArgument.ToString().Split(',');
prjID = Convert.ToInt32(array[1].ToString());
Int32 bid = Convert.ToInt32(array[0].ToString());
Hashtable ht = new Hashtable();
ht.Clear();
userN = Convert.ToString(lnk.ToolTip);
ViewState["logincheck"] = userN;
string mal = getUserMail(userN);
string prtit = getProjectTitle(prjID);
ViewState["eMail"] = mal;
accountType = "bid on " + prtit;
ht.Add("@bid", bid);
ht.Add("@prjID", prjID);
if (lnk.Text == "Deactivate")
{
chk = "Activated";
ht.Add("@isactive", Convert.ToBoolean("False"));
NSBuilder.DataAccess.ExecuteNonQuery("sp_activeBidStatus", ht);
lnk.Text = "Activate";
mailStatus = "DeActivated";
lblmsg.Visible = true;
lblmsg.Text = userN + " bid is DeActivated.";
//sendMail();
chk = "";
string javaScript =
"<script language=JavaScript>\n" +
"alert('" + userN + " bid has been DeActivated. !!');\n" +
"</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "onload", javaScript);
}
else
{
chk = "DeActivated";
ht.Add("@isactive", Convert.ToBoolean("True"));
NSBuilder.DataAccess.ExecuteNonQuery("sp_activeBidStatus", ht);
lnk.Text = "Deactivate";
mailStatus = "Activated";
lblmsg.Visible = true;
lblmsg.Text = userN + " bid is Activated.";
// sendMail();
chk = "";
string javaScript =
"<script language=JavaScript>\n" +
"alert('" + userN + " bid has been Activated. !!');\n" +
"</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "onload", javaScript);
}
// searchMethod();
}
IMAGE TYPE VALIDATION IN FILE UPLOAD CONTROL
0 comments Saturday, November 13, 2010 Posted by Vikas SharmaLabels: FILE_UPLOAD, VALIDATIONS
IMAGE TYPE VALIDATION IN FILE UPLOAD CONTROL
-------------------------------------------
<td>
<asp:FileUpload ID="FileUpload1" runat="server" CssClass="textbox_reg" Width="210px" />
<asp:RegularExpressionValidator ID="rfv_FileUpload1" runat="server" ErrorMessage="Invalid file name! select only image file types."
ValidationExpression=".*(\.[Jj][Pp][Gg]|\.[Gg][Ii][Ff]|\.[Pp][Nn][Gg]|\.[Jj][Pp][Ee][Gg]|\.[Bb][Mm][Pp])"
Display="None" ControlToValidate="FileUpload1">*</asp:RegularExpressionValidator>
<cc1:ValidatorCalloutExtender ID="vce_imagebefore1" TargetControlID="rfv_FileUpload1" runat="server">
</cc1:ValidatorCalloutExtender>
</td>
FILE UPLOAD THUMBNAIL
0 comments Saturday, November 13, 2010 Posted by Vikas SharmaLabels: Asp.net Utility Functions, FILE_UPLOAD
FILE UPLOAD CONTROLif(FU_Product.FileName != "")
{
Int32 intFileSize = Convert.ToInt32(FU_Product.PostedFile.ContentLength);
if(intFileSize <= 1000000)
{
String[] fileNameArray = FU_Product.FileName.Split('.');
string fileSavePath;
string origFileName;
string newFileName;
fileSavePath = "Images/";
origFileName = fileNameArray[0].ToString();
newFileName = Guid.NewGuid().ToString() + "." + fileNameArray[1];
FU_Product.SaveAs(Server.MapPath(fileSavePath + newFileName));
System.Drawing.Image Img = System.Drawing.Image.FromStream(FU_Product.PostedFile.InputStream);
Int32 thumbSize = 150;
Int32 width, height;
height = thumbSize;
width = Img.Width * thumbSize / Img.Height;
System.Drawing.Image thumbnailImage = Img.GetThumbnailImage(width, height, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
thumbnailImage.Save(Server.MapPath(fileSavePath + "T" + newFileName));
parm[4] = new SqlParameter("@Image", SqlDbType.VarChar, 50);
parm[4].Value = newFileName.ToString();
}
else
{
lblError.Text = "File size should be < 1 MB.";
}
}
private bool ThumbnailCallback()
{
return true;
}
FUNCTION TO CLEAR THE CONTROLS
0 comments Saturday, November 13, 2010 Posted by Vikas SharmaLabels: Asp.net Utility Functions
-------------------------------------------------
FUNCTION TO CLEAR THE CONTROLS
public void ClearControls(Control parent )
{
foreach (Control c in parent.Controls)
{
if (c.Controls.Count > 0)
{
ClearControls(c);
}
else
{
switch (c.GetType().ToString())
{
case "System.Web.UI.WebControls.TextBox" :
((TextBox)c).Text = "";
break;
case "System.Web.UI.WebControls.DropDownList":
((DropDownList)c).SelectedIndex = -1;
break;
}
}
}
}
Anchor_LinkButtons_Gridview
0 comments Saturday, November 13, 2010 Posted by Vikas SharmaLabels: GridViewLinkButtons
----------------------------------------------------------------------------------
<ItemTemplate>
<asp:LinkButton ID="lnkview" runat="server" CommandName="viewProject"
CommandArgument='<%#Eval("ID") %>'
CssClass="tahomatext"><img src="../images/icon_details.png" style="border:0;" alt="Bidding Details" title="Bidding Details" /></asp:LinkButton>
</ItemTemplate>
--------------------------------------
protected void grdProject_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToString() == "viewProject")
{
uid = Convert.ToInt32(e.CommandArgument.ToString());
Response.Redirect("BidDetails.aspx?pid=" + uid);
}
}
************************************************
<ItemTemplate>
<a href="addFeedBackLister.aspx?pid=<%#Eval("ID") %>&cid=<%#Eval("ContractorID") %>"
title="Give feedback"
class='<%#visibleBtn(Convert.ToInt64(Eval("ID")))%>'>
<img src="../images/reviewadd.png" height="25" width="25" border="0px" />
</a>
</ItemTemplate>
-----------------------------------
public String visibleBtn(Int64 pid)
{
Hashtable ht = new Hashtable();
ht.Clear();
ht.Add("@pid", pid);
Int32 result = NSBuilder.DataAccess.ExecuteNonQueryWithReturnParameter("Usp_AlreadyRated", ht);
if (result == 1)
{
return "visible";
}
else
{
return "hide";
}
}
********************************************
Note:-- no runat attribute
<a href='viewZipCode.aspx?s=<%#Eval("TState")%>&c=<%#Eval("TCounty") %>'
onclick="return hs.htmlExpand(this, { objectType: 'iframe' } )"> View Zip </a>
*******************************************
<ItemTemplate>
<a href="UpdateFranchiseeProfile.aspx?uid='<%#Eval("FranchID") %>'&mail=<%#Eval ("Email") %>"><%#Eval("UserName") %>
</a>
</ItemTemplate>
********************************************
<ItemTemplate>
<asp:LinkButton ID="lnkApprove" CommandName="Approve"
CommandArgument='<%#Eval("RID") %>'
CssClass='<%#visibleBtn(Convert.ToInt64(Eval("RID"))) %>'
runat="server">Approved</asp:LinkButton>
</ItemTemplate>
******************************************
<ItemTemplate>
<asp:LinkButton ID="lnkbtnIsactive" runat="server" OnClick="change_status" ToolTip='<%#Eval("UserName")%>'
Text='<%#get(Convert.ToBoolean((Eval("IsActive"))))%>' CssClass="tahomatext"></asp:LinkButton>
</ItemTemplate>
################################
<%-- NO runat tag in <anchor> --%>
<ItemTemplate>
<a href="ProductDetails.aspx?pid=<%#Eval("ID")%>">
<img src="Images/<%#Eval("Image") %>" alt="image" />
</a>
</ItemTemplate>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<a href="UpdateSubAdmin.aspx?ud=<%#Eval("UserID") %>&un=<%#Eval("UserName") %>">
<img src="../images/Edit.png" style="border: 0;" alt="Edit Sub Admin" title="Edit Sub Admin" />
</a>
</ItemTemplate>
</asp:TemplateField>
************************************************
Sunday, November 7, 2010
Login PopUp
0 comments Sunday, November 07, 2010 Posted by Vikas SharmaLabels: PopUp
----------------------------------------------------------------------------------
(Open Login box in a PopUp)
<head>
<link href="highslide/highslide.css" rel="stylesheet" type="text/css" />
<script src="highslide/highslide-with-html.js" type="text/javascript"></script>
<script type="text/javascript">
hs.graphicsDir = 'highslide/graphics/';
hs.outlineType = 'rounded-white';
hs.wrapperClassName = 'draggable-header';
</script>
</head>
---------------------
<td align="left" class="verdana10normalcream">
<a href="user/register.aspx" class="arial11normalwhite"
onclick="return hs.htmlExpand(this, { objectType: 'iframe' } )"> new user?</a>
</td>
----------------------------------------
(Register.aspx)
----------------------------------------
<asp:RadioButtonList ID="rblUserType" ToolTip="Select a User Type!!" CssClass="treb14normaldarkred" runat="server" CellPadding="1" CellSpacing="3" Height="122px" Width="196px">
<asp:ListItem Value="1">Project Lister</asp:ListItem>
<asp:ListItem Value="2">Professional</asp:ListItem>
<asp:ListItem Value="3">Franchisee</asp:ListItem>
</asp:RadioButtonList>
-----------------------------------------
(Code on register.aspx)
protected void btnContinue_Click(object sender, ImageClickEventArgs e)
{
if (rblUserType.SelectedIndex == -1)
{
// below script also works
//string javaScript =
// "<script language=JavaScript>\n" +
// "alert('please select before proceeding!!');\n" +
// "</script>";
//Page.ClientScript.RegisterStartupScript(this.GetType(), "onload", javaScript);
}
else
{
string scriptString;
switch (Convert.ToInt32(rblUserType.SelectedItem.Value))
{
case 1:
scriptString = "<script language=JavaScript>" +
"window.opener.document.forms(0).submit(); window.close();</script>";
if (!Page.ClientScript.IsClientScriptBlockRegistered(scriptString))
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
"script", scriptString);
}
Response.Write("<script>window.top.location=\"../Lister/register_lister.aspx\"</script>");
break;
case 2:
scriptString = "<script language=JavaScript>" +
"window.opener.document.forms(0).submit(); window.close();</script>";
if (!Page.ClientScript.IsClientScriptBlockRegistered(scriptString))
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
"script", scriptString);
}
Response.Write("<script>window.top.location=\"../Prof/register_contractor.aspx\"</script>");
break;
case 3:
scriptString = "<script language=JavaScript>" +
"window.opener.document.forms(0).submit(); window.close();</script>";
if (!Page.ClientScript.IsClientScriptBlockRegistered(scriptString))
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
"script", scriptString);
}
Response.Write("<script>window.top.location=\"../Franchisee/register_franchisee.aspx\"</script>");
break;
}
}
}
-------------------------------------
HighSlidePopUp(CodeBehind Values)
0 comments Sunday, November 07, 2010 Posted by Vikas SharmaLabels: PopUp
----------------------------------------------------------------------------------
(When values are available in code behind eg. in viewstate etc.)
-------------------------------
<link href="../highslide/highslide.css" rel="stylesheet" type="text/css" />
<script src="../highslide/highslide-with-html.js" type="text/javascript"></script>
-------------
<script type="text/javascript">
hs.graphicsDir = '../highslide/graphics/';
hs.outlineType = 'rounded-white';
hs.wrapperClassName = 'draggable-header';
</script>
-------------------------
<a href='viewZipCode.aspx?s=<%=Convert.ToString(ViewState["state"]) %>&c=<%=Convert.ToString(ViewState["county"]) %>'
onclick="return hs.htmlExpand(this, { objectType: 'iframe' } )">
<img id="imgviewZip" src="../images/view.png" border="0" />
</a>
------------------------------------
Saturday, November 6, 2010
HighSlide PopUp IFrame
0 comments Saturday, November 06, 2010 Posted by Vikas SharmaLabels: PopUp
----------------------------------------------------------------------------------
(When values are availabe in HTML i.e In Eval)
---------------------
<link href="../highslide/highslide.css" rel="stylesheet" type="text/css" />
<script src="../highslide/highslide-with-html.js" type="text/javascript"></script>
-----------------------
<script type="text/javascript">
hs.graphicsDir = '../highslide/graphics/';
hs.outlineType = 'rounded-white';
hs.wrapperClassName = 'draggable-header';
</script>
-------------------------
<asp:TemplateField>
<ItemTemplate>
<%-- <a href='viewZipCode.aspx?s=<%#Eval("TState")%>&c=<%#Eval("TCounty") %>'>view Zipcodes</a>--%>
<a class="textbidtip" href='viewZipCode.aspx?s=<%#Eval("TState")%>&c=<%#Eval("TCounty") %>'
onclick="return hs.htmlExpand(this, { objectType: 'iframe' } )">View Zip </a>
</ItemTemplate>
</asp:TemplateField>
------------------------------------
****************************************************************
<em>
<U>TO CLOSE IFRAME FROM A BUTTON INSIDE IT</U>
<U>AND TO REDIRECT TO ANOTHER PAGE AFTER SUBMIT FROM IFRAME</U>
<tr>
<td align="right" style="width: 50%">
<asp:ImageButton ID="btnSubmit" ImageUrl="~/images/submit_btn.jpg" runat="server"
ValidationGroup="R" ToolTip="Submit" OnClick="btnSubmit_Click" />
</td>
<td align="left" style="width: 50%; padding-left: 30px;">
<input id="Button1" type="button" style="background-image: images/cancel_btn.jpg;"
value="Cancel"
onclick="javascript:parent.window.hs.close();" />
</td>
</tr>
protected void btnSubmit_Click(object sender, ImageClickEventArgs e)
{
string scriptString = "<script language=JavaScript>" +
"window.opener.document.forms(0).submit(); window.close();</script>";
if (!Page.ClientScript.IsClientScriptBlockRegistered(scriptString))
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
"script", scriptString);
}
Response.Write("<script>window.top.location=\"ManageTheme.aspx\"</script>");
}
</em>
Sunday, October 3, 2010
GridviewTips
0 comments Sunday, October 03, 2010 Posted by Vikas SharmaLINK BUTTON IN GRIDVIEW:-
----------------------------------------------------------------------------------
<ItemTemplate>
<asp:LinkButton ID="lnkview" runat="server" CommandName="viewProject"
CommandArgument='<%#Eval("ID") %>'
CssClass="tahomatext"><img src="../images/icon_details.png" style="border:0;" alt="Bidding Details" title="Bidding Details" /></asp:LinkButton>
</ItemTemplate>
--------------------------------------
protected void grdProject_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToString() == "viewProject")
{
uid = Convert.ToInt32(e.CommandArgument.ToString());
Response.Redirect("BidDetails.aspx?pid=" + uid);
}
}
-------------------------------------------------------------------
ANCHOR TAG IN GRIDVIEW:-
<ItemTemplate>
<a href="addFeedBackLister.aspx?pid=<%#Eval("ID") %>&cid=<%#Eval("ContractorID") %>"
title="Give feedback" class='<%#visibleBtn(Convert.ToInt64(Eval("ID")))%>'>
<img src="../images/reviewadd.png" height="25" width="25" border="0px" /></a>
</ItemTemplate>
-----------------------------------------------------------------
GRIDVIEW PAGER FORMATTING
protected void grdBidHistory_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(grdBidHistory.PageIndex, tc);
tbl.Rows[0].Cells.AddAt(grdBidHistory.PageIndex + 2, tc1);
}
}
---------------------------------------------------------------------
NULL VALUE RECORD CHECK FOR GRIDVIEW
My Table in database look like as shown in image, some columns contains NULL values and i'll be showing "No Records Found" instead of NULL values in GridView.
To achieve this i've written a Method in code behind and will be calling this method in ItemTemplate of GridView.
call this server side method CheckNull written in code behind from ItemTemplate of GridView which check the NULL values and change it as we want.
C# code for the CheckNull method
protected string CheckNull(object objGrid)
{
if (object.ReferenceEquals(objGrid, DBNull.Value))
{
return "No Record Found";
}
else
{
return objGrid.ToString();
}
}
To create mailTo link
0 comments Sunday, October 03, 2010 Posted by Vikas SharmaLabels: GeneralTips n Tricks
<td align="left" class="textgridtext">
<asp:HyperLink ID="lnkMail" runat="server"></asp:HyperLink>
</td>
lnkMail.Text = dt.Rows[0]["Email"].ToString();
lnkMail.NavigateUrl = "Mailto:" + dt.Rows[0]["Email"].ToString();
IntArrayToCommaString Function
0 comments Sunday, October 03, 2010 Posted by Vikas SharmaLabels: Asp.net Utility Functions
public static string IntArrayToCommaString(int[] intArray)
{
string s = "";
foreach (int i in intArray)
{
s += intArray[i].ToString() + ",";
}
return s.TrimEnd(',');
}
Convert commaStringToIntArray Function
0 comments Sunday, October 03, 2010 Posted by Vikas SharmaLabels: Asp.net Utility Functions
String strCategory = Convert.ToString(dt.Rows[0]["ProjectCategoriesAlert"]);
int[] category = clsBuilder.commaStringToIntArray(strCategory);
for (int i = 0; i < category.Length; i++)
{
cbl_Categories.Items[category[i] - 1].Selected = true;
}
----------------------------------------------------------
public static int[] commaStringToIntArray(string str)
{
String[] strArray = str.Split(',');
int[] intArray = new int[strArray.Length];
for (int i = 0; i < strArray.Length; i++)
{
intArray[i] = int.Parse(strArray[i]);
}
return intArray;
}
-----------------------------------------------------------------------
string str = string.Empty;
for (int i = 0; i < cbl_Categories.Items.Count; i++)
{
if (cbl_Categories.Items[i].Selected == true)
{
str += cbl_Categories.Items[i].Value + ",";
}
}
Email Already Exists(Ajax)
0 comments Sunday, October 03, 2010 Posted by Vikas SharmaLabels: VALIDATIONS
<td align="left" valign="top">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtEmail" AutoPostBack="true" CssClass="textbox_reg"
OnTextChanged="txtEmail_TextChanged" MaxLength="50" runat="server"></asp:TextBox>
<div id="UserAvailability" runat="server" class="messages"></div>
</ContentTemplate>
</asp:UpdatePanel>
<asp:RequiredFieldValidator ID="rfv_email" ValidationGroup="submit" runat="server"
ErrorMessage="Please enter the Email."
ControlToValidate="txtEmail" Display="Dynamic"
Font-Size="X-Small" SetFocusOnError="True">*</asp:RequiredFieldValidator>
<cc1:ValidatorCalloutExtender TargetControlID="rfv_email" ID="VCE_email" runat="server">
</cc1:ValidatorCalloutExtender>
<asp:RegularExpressionValidator ID="rev_email" ValidationGroup="submit" runat="server"
ErrorMessage="Email not in proper format.Please enter again." ControlToValidate="txtEmail"
Display="Dynamic" Font-Size="X-Small" SetFocusOnError="True" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator>
<cc1:ValidatorCalloutExtender TargetControlID="rev_email" ID="VCE_emailFormat" runat="server"></cc1:ValidatorCalloutExtender>
</td>
protected void txtEmail_TextChanged(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string sql = "select Email From tbl_user Where Email='" + txtEmail.Text.Trim() + "'";
dt = NSBuilder.DataAccess.GetDataSetwitrhcommand(sql).Tables[0];
if (dt.Rows.Count > 0)
{
UserAvailability.InnerText = "Email already taken,Please change!!";
}
else
{
UserAvailability.InnerText = "";
}
}
Checkbox validation
0 comments Sunday, October 03, 2010 Posted by Vikas SharmaLabels: VALIDATIONS
<script type="text/javascript" language="javascript">
function ValidateCheckBox(src, args) {
if (document.getElementById('<%=chk_Terms.ClientID %>').checked == false) {
alert("Please check Terms & Conditions before continuing.");
//return false;
args.IsValid = false;
}
}
------------------------------------------------
<asp:CheckBox ID="chk_Terms" runat="server" CssClass="arial11normalblack" Text="I agree to the Terms & Cconditions" />
<asp:CustomValidator ValidationGroup="submit" ID="cv_Checkbox" runat="server" ClientValidationFunction="ValidateCheckBox"
Display="None" SetFocusOnError="True">*</asp:CustomValidator>
At least n Characters required
0 comments Sunday, October 03, 2010 Posted by Vikas SharmaLabels: VALIDATIONS
-------------------------------------------------------------------
Last Name: <ASP:TEXTBOX id=TxtLastName runat="server"></ASP:TEXTBOX><ASP:REGULAREXPRESSIONVALIDATOR id=REVLastName runat="server" controltovalidate="TxtLastName" errormessage="please enter at least 3 charaters"
validationexpression="[0-9a-zA-Z]{3,}"></ASP:REGULAREXPRESSIONVALIDATOR>
� Here we used RegularExpressionValidator to validate that user enter at least 3 characters in the Last name TextBox by add this regular expression [0-9a-zA-Z]{3,}.
Javascript validation on multiline texbox for character count
0 comments Sunday, October 03, 2010 Posted by Vikas SharmaLabels: VALIDATIONS
<script language="javascript">
function validateLimit(obj, divID, maxchar) {
objDiv = get_object(divID);
if (this.id) obj = this;
var remaningChar = maxchar - trimEnter(obj.value).length;
if (objDiv.id) {
objDiv.innerHTML = remaningChar + " characters left";
}
if (remaningChar <= 0) {
obj.value = obj.value.substring(maxchar, 0);
if (objDiv.id) {
objDiv.innerHTML = "0 characters left";
}
return false;
}
else
{ return true; }
}
function get_object(id) {
var object = null;
if (document.layers) {
object = document.layers[id];
} else if (document.all) {
object = document.all[id];
} else if (document.getElementById) {
object = document.getElementById(id);
}
return object;
}
function trimEnter(dataStr) {
return dataStr.replace(/(\r\n|\r|\n)/g, "");
}
</script>
-------------------------
<asp:TextBox ID="txtprojectdesc"
MaxLength="240" CssClass="textbox_reg" TextMode="MultiLine"
Rows="5" Width="200px"
ToolTip="Summary:(240 characters)"
onkeyup="return validateLimit(this, 'lblMsg1',240)"
runat="server">
</asp:TextBox><br />
<div id="lblMsg1" class="messagetip">240 characters left</div>
JQuery validation on multiline textbox for character count
0 comments Sunday, October 03, 2010 Posted by Vikas SharmaLabels: VALIDATIONS
-------------------------------------------------------------------
JQuery validation on multiline textbox for character count
-------------------------------------------------------------------
<script src="../scripts/jquery-1.4.2.js" type="text/javascript"></script>
<script language="javascript">
$(document).ready(function() {
//Set the Variable for max length
var MaxLength = 50;
$('#<%=txtCount.ClientID%>').val(MaxLength);
$('#<%=txtprojectdesc.ClientID%>').keyup(function() {
if ($(this).text().length > MaxLength) {
$(this).text($(this).text().substring(0, MaxLength));
}
$('#<%=txtCount.ClientID%>').val(MaxLength - $(this).text().length);
});
$('#<%=txtprojectdesc.ClientID%>').blur(function() {
if ($(this).text().length > MaxLength) {
$(this).text($(this).text().substring(0, MaxLength));
}
$('#<%=txtCount.ClientID%>').val(MaxLength - $(this).text().length);
});
});
</script>
--------------------------------------
<asp:TextBox ID="txtprojectdesc" CssClass="textbox_reg" TextMode="MultiLine" Rows="5" Width="200px" runat="server"></asp:TextBox><br />
<asp:TextBox ID="txtCount" MaxLength="3" ReadOnly="true" BorderWidth="0" CssClass="textbox_reg" Width="20px" Font-Names="verdana" Font-Size="XX-Small"
ForeColor="#ad1800" runat="server"></asp:TextBox><span class="helptext">Characters left.</span>
Saturday, October 2, 2010
To post HTML/Java Code in your blog posts
0 comments Saturday, October 02, 2010 Posted by Vikas SharmaLabels: GeneralTips n Tricks
To post HTML/Java Code in your blog posts ... use this link...
http://centricle.com/tools/html-entities/
After converting the code , paste it into your blog between <blockquote> tags...
for eg.
<blockquote>
-- your code from http://centricle.com/tools/html-entities/
</blockquote>
<a href="http://bloggerstop.net/2008/10/blogger-help-how-to-show-html-text-in.html">Please see here to remove </em> tag and to add Blockquote tags</a>
-------------------------------------
Removing the blogger navigation bar from a template
0 comments Saturday, October 02, 2010 Posted by Vikas SharmaLabels: GeneralTips n Tricks
--------------------------------------------
Removing the blogger navigation bar from a template
Go to your blogger dashboard> layout> edit HTML. Search this code,
]]>
Now add this code above the code,
#navbar-iframe {height:0px;visibility:hidden;display:none}
With this trick, you can remove the navbar from any blogger template
----------------------
To control excess data to display in gridview cell
0 comments Saturday, October 02, 2010 Posted by Vikas SharmaLabels: GeneralTips n Tricks
------------------------------------------------------------
To control excess data to display in gridview cell
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.DataRow)
{
ViewState["Data"] = e.Row.Cells[1].Text;
if (e.Row.Cells[1].Text.Length > 25)
{
e.Row.Cells[1].Text = e.Row.Cells[1].Text.Substring(0, 25) + “…”;
e.Row.Cells[1].ToolTip = ViewState["Data"].ToString();
}
-----------------------
Change row color in Gridview on mouse over
0 comments Saturday, October 02, 2010 Posted by Vikas SharmaLabels: GeneralTips n Tricks
----------------------------------------------------------------
Change row color in Gridview on mouse over
If you have the need to change the row color of a row in a gridview when you mouse over (and mouse out) you can add some code to the RowDataBound event.
Here is a sample:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Only apply to data rows
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Add mouse over event to change row background color
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor=’Yellow’");
//Add mouse out event to change row background color back to white
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=White");
}
}
-----------------------
GridView with clickable rows
0 comments Saturday, October 02, 2010 Posted by Vikas SharmaLabels: GeneralTips n Tricks
-------------------------------------------------------------------
GridView with clickable rows
If you need to have a GridView with rows that you can click on you will need to set the onClick event for each row.
Here is a code sample for the RowDataBound event of a GridView.
This examples pulls the value of cell 0 and appends it to the url.
protected void grd_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridView grid = (GridView)sender as GridView;
//Only format data rows
if (e.Row.RowType == DataControlRowType.DataRow)
{
string urlLink = “Link?number=” + e.Row.Cells[0].Text.ToString();
e.Row.Attributes["onClick"] = "location.href=’" + urlLink + "’";
}
}
-----------------------
Gridview Pager Formatting
0 comments Saturday, October 02, 2010 Posted by Vikas SharmaLabels: GeneralTips n Tricks
-------------------------------------------------------------
protected void grdBidHistory_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(grdBidHistory.PageIndex, tc);
tbl.Rows[0].Cells.AddAt(grdBidHistory.PageIndex + 2, tc1);
}
}
-----------------------
Null value record check for gridview
0 comments Saturday, October 02, 2010 Posted by Vikas SharmaLabels: GeneralTips n Tricks
My Table in database look like as shown in image, some columns contains NULL values and i'll be showing "No Records Found" instead of NULL values in GridView.
To achieve this i've written a Method in code behind and will be calling this method in ItemTemplate of GridView.
call this server side method CheckNull written in code behind from ItemTemplate of GridView which check the NULL values and change it as we want.
C# code for the CheckNull method
protected string CheckNull(object objGrid)
{
if (object.ReferenceEquals(objGrid, DBNull.Value))
{
return "No Record Found";
}
else
{
return objGrid.ToString();
}
}
Format Gridview Cell Data with OnRowCreated function
0 comments Saturday, October 02, 2010 Posted by Vikas SharmaLabels: GeneralTips n Tricks
---------------------------------------------------------------------
Format Gridview Cell Data with OnRowCreated function
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;
}
}
----------------------------------------------------------------------
caseSyntax
0 comments Saturday, October 02, 2010 Posted by Vikas SharmaLabels: Sql_GeneralStatements
------------------------------------------
CASE WHEN EXISTS(select doc.id from tbl_Document doc where doc.ProjectID=prj.ID)
THEN 'Yes'
ELSE
'No'
END AS ATTACHED_FILES
-------------------------------------------
SELECT
ISNULL('$ ' + CONVERT(varchar(100), tbl_Contractor.Balance) + ' USD', '$ 0 USD ') as Balance
FROM tbl_Contractor where tbl_Contractor.UserID=@cid
--------------------------------------------
ISNULL('$ '+CONVERT(varchar(100),tbl_Bid.BidAmount)+' USD','N/A')
as BidAmount
--------------------------------------------
isnull(convert(varchar(100),tbl_Bid.DeliveryTime)+' Day(s)','N/A') as DeliveryTime
--------------------------------------------
TableToString_ListToTable_Use2
0 comments Saturday, October 02, 2010 Posted by Vikas SharmaLabels: TableToString_ListToTable_Use
ALTER PROCEDURE [dbo].[Usp_GetAllProjects_ByCategory]
(
@categoryid bigint
)
AS -- [Usp_GetAllProjects_ByCategory] '34'
BEGIN
SELECT tbl_Project.ID,tbl_User.UserName,
CASE
WHEN LEN(tbl_Project.ProjectTitle) > 150
THEN SUBSTRING(tbl_Project.ProjectTitle,0,150) + '...'
ELSE
CASE
WHEN LEN(tbl_Project.ProjectTitle) < 150
THEN tbl_Project.ProjectTitle
ELSE
tbl_Project. ProjectTitle
END
END
AS ProjectTitle,
CONVERT(varchar(50), tbl_Project.DateCreated,106) as DateCreated,
dbo.TableToString(tbl_Project.CategoryID) as Category,
(select count(*) from tbl_Bid where tbl_Bid.ProjectID = tbl_Project.ID ) as Bids
FROM tbl_Project inner join tbl_User
on tbl_Project.UserID = tbl_User.UserID
where tbl_Project.IsActive=1 and tbl_Project.ProjectStatus='Open'
AND
EXISTS (select entry from ListToTable(tbl_Project.CategoryID)where entry=@categoryid)
ORDER BY ID DESC
END
IF @@ERROR <> 0
RETURN -1
ELSE
RETURN 1
TableToString_ListToTable_Use1
0 comments Saturday, October 02, 2010 Posted by Vikas SharmaLabels: TableToString_ListToTable_Use
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER PROCEDURE [dbo].[Usp_GetAllProjectsByLister]
(
@email VARCHAR(50)
) -- [Usp_GetAllProjectsByLister] 'a@a.com'
AS
DECLARE @userid bigint
SET @userid = (Select UserID from tbl_User where Email=@email)
BEGIN
SELECT ID, ProjectTitle,Description,CONVERT(varchar(50),DateCreated,106) as DateCreated,
dbo.TableToString(tbl_Project.CategoryID) as Category,
tbl_project.DaysOpenForBids,
(select count(*) from tbl_Bid where tbl_Bid.ProjectID = tbl_Project.ID ) as Bids,tbl_Project.ProjectStatus,
CASE
WHEN 0 < DATEDIFF(DAY,GETDATE(),
DateAdd(Day,tbl_project.DaysOpenForBids,tbl_Project.DateCreated))
THEN
CONVERT(varchar,DATEDIFF(DAY,GETDATE() ,
DateAdd(Day,tbl_project.DaysOpenForBids,tbl_Project.DateCreated))) + ' Day(s)'
ELSE
CASE
WHEN 0=DATEDIFF(DAY,GETDATE() ,
DateAdd(Day,tbl_project.DaysOpenForBids,tbl_Project.DateCreated))
THEN
'Today'
ELSE
'0 Day(s)'
END
END
AS DaysOpen
FROM tbl_Project
WHERE UserID=@userid
ORDER BY ID DESC
END
IF @@ERROR <> 0
RETURN -1
ELSE
RETURN 1
TableToString_ListToTable_Use
0 comments Saturday, October 02, 2010 Posted by Vikas SharmaLabels: TableToString_ListToTable_Use
ALTER procedure [dbo].[Usp_ProfessionalEmails_ProjectActivated]
(
@pid bigint
) -- Usp_ProfessionalEmails_ProjectActivated '21'
AS
declare @ptitle varchar(500)
set @ptitle=(select tbl_Project.ProjectTitle from tbl_Project where tbl_Project.ID=@pid)
declare @listername varchar(100)
set @listername=(select tbl_User.UserName from tbl_User inner join tbl_Project on tbl_User.UserID=tbl_Project.UserID and tbl_Project.ID=@pid )
select @ptitle as ProjectTitle,@listername as ListerName
select tbl_Contractor.ID,tbl_User.UserName,tbl_User.Email from tbl_Contractor inner join tbl_User on tbl_Contractor.UserID=tbl_User.UserID
where exists
(
select entry from dbo.ListToTable
(
(select tbl_Project.CategoryID from tbl_Project where tbl_Project.ID=@pid)
)
where entry in (select e.entry from ListToTable(ProjectCategoriesAlert) e)
)
-----------------------------------------------------------
-----------------------------------------------------------
List down the DataType and Size Of all Columns of All Tables in a SQL Server 2005/2008 Database
0 comments Saturday, October 02, 2010 Posted by Vikas SharmaLabels: SQL_SPs
-----------------------------------------------------------------------------
List down the DataType and Size Of all Columns of All Tables in a SQL Server 2005/2008 Database
--------------------------------------------------------
if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[UTILfn_Split]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[UTILfn_Split]
GO
create function dbo.UTILfn_Split(
@String nvarchar (4000),
@Delimiter nvarchar (10)
)
returns @ValueTable table ([Value] nvarchar(4000))
begin
declare @NextString nvarchar(4000)
declare @Pos int
declare @NextPos int
declare @CommaCheck nvarchar(1)
--Initialize
set @NextString = ''
set @CommaCheck = right(@String,1)
--Check for trailing Comma, if not exists, INSERT
--if (@CommaCheck <> @Delimiter )
set @String = @String + @Delimiter
--Get position of first Comma
set @Pos = charindex(@Delimiter,@String)
set @NextPos = 1
--Loop while there is still a comma in the String of levels
while (@pos <> 0)
begin
set @NextString = substring(@String,1,@Pos - 1)
insert into @ValueTable ( [Value]) Values (@NextString)
set @String = substring(@String,@pos +1,len(@String))
set @NextPos = @Pos
set @pos = charindex(@Delimiter,@String)
end
return
end
--------------------------------------------
/*
Util_ListDBSchema N'MyDatabase', N'tbl_Class,MyTempTable1' –several tables
Util_ListDBSchema N'MyDatabase', N'*' –-all tables
Util_ListDBSchema N'MyDatabase', N'tbl_movies' –one table
*/
---------------------------------------------
CREATE PROCEDURE dbo.Util_ListDBSchema
(
@dbName varchar(100),
@tableName varchar(500)
)
AS -- Util_ListDBSchema 'ServiceMatchMaker','*'
BEGIN
SET NOCOUNT ON;
DECLARE @strSql varchar(2500), @strWhere varchar(1000)
--list tables only
SET @strWhere = 'objectproperty(object_id(table_name),''IsTable'') = 1'
IF (@tableName <> '*')
SET @strWhere = @strWhere + 'and
table_name in (SELECT * from dbo.UTILfn_Split ('''+@tableName+''','',''))'
SET @strSQL = N'
USE ['+ @dbName +']
SELECT
table_catalog, table_schema, table_name, column_name,
data_type, character_maximum_length as max_length
FROM information_schema.columns
WHERE '+@strWhere+' ORDER BY table_name, column_name'
-- print @strSQL
exec (@strSQL)
END
GO
SQL_Utility_StoredProcs
0 comments Saturday, October 02, 2010 Posted by Vikas SharmaLabels: SQL_Utility_StoredProcs
TO FIND STORED PROCEDURE CREATED WITHIN CERTAIN TIME RANGE
------------------------------------------------------------------
SELECT name
FROM sys.objects
WHERE type = 'P'
--AND DATEDIFF(D,create_date, GETDATE()) < 2
AND DATEDIFF(D,modify_date, GETDATE()) < 2
-------------------------------------------------------------------
TO FIND TABLES CREATED/MODIFIED WITHIN CERTAIN TIME RANGE
SELECT [name],create_date,modify_date FROM sys.Tables
WHERE modify_date > DATEADD(day,-2,GETDATE())
----------
SELECT name
FROM sys.objects
WHERE DATEDIFF(D,modify_date, GETDATE()) < 2
ORDER BY NAME ASC
-------------------------------------------------------------------
TO FIND TABLES/VIEWS CREATED/MODIFY WITHIN CERTAIN TIME RANGE
-------------------------------------------------------------------
SELECT [name],create_date,modify_date FROM sys.tables
order by modify_date desc
----------------------
SELECT [name],create_date,modify_date FROM sys.views
WHERE modify_date > DATEADD(day,-30,GETDATE())
-------------------------------------------------------------------
TO FIND ALL REFERENCES TO A COLUMN IN STORED PROCUDURES>
FINDING STORED PROCEDURES THAT REFERENCE\UPDATE A COLUMN
---------------------------------------------------------------------
select object_name(id)
from sysdepends
where depid = object_id('tbl_Directory')
and col_name(depid, depnumber) = 'IsRegistered'
order by 1
-----------------------------------------------------------------------
TO FIND TOTAL STORED PROCEDURE COUNT IN A DATABASE
----------------------------
select count(1) from sys.objects where type='P'
-------------------------------------------------------------------------
TO FIND STORED PROCS RELATED TO A TABLE IN DATABASE
SEARCH IN ALL STORED PROCEDURES
-----------------------------------
SELECT DISTINCT so.name
FROM syscomments sc
INNER JOIN sysobjects so ON sc.id=so.id
WHERE sc.TEXT LIKE '%tbl_Territory%'
----------------------------------------------------------------------
TO FIND A STORED PROCEDURE CONTAINING SOME TEXT OR COLUMN NAME
-------------------------------------------------------------------------
SELECT ROUTINE_NAME, ROUTINE_DEFINITION
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE '%TCounty%'
AND ROUTINE_TYPE='PROCEDURE'
-------------------------------------------------------------------------
TO FIND THE MODIFIED TABLES IN A DATABASE
------------------------------------------------
select name,create_date,modify_date from sys.tables
WHERE create_date <> modify_date
ORDER BY modify_Date
------------------------------------------------------------------------
TO FIND INFORMATION ABOUT DATABASE OBJECTS
-----------------------------------------------------------------------
SELECT Specific_Catalog,
Specific_Name,
Routine_Catalog,
Routine_Type,
Routine_Definition,
Created,
Last_Altered
FROM INFORMATION_SCHEMA.ROUTINES
WHERE Created <> Last_Altered
ORDER BY Last_Altered
--------------------------------------------------------
TO GET THE COLUMN NAMES AND DATATYPES IN A TABLE
------------------------------------------------------------------------
USE CRMK
GO
SELECT column_name 'Column Name',
data_type 'Data Type',
character_maximum_length 'Maximum Length'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'Country'
--------------------------------------------------------------------------
[dbo].[UTILfn_Split]
0 comments Saturday, October 02, 2010 Posted by Vikas SharmaLabels: SQLFunctions
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER function [dbo].[UTILfn_Split](
@String nvarchar (4000),
@Delimiter nvarchar (10)
)
returns @ValueTable table ([Value] nvarchar(4000))
begin
declare @NextString nvarchar(4000)
declare @Pos int
declare @NextPos int
declare @CommaCheck nvarchar(1)
--Initialize
set @NextString = ''
set @CommaCheck = right(@String,1)
--Check for trailing Comma, if not exists, INSERT
if (@CommaCheck <> @Delimiter)
set @String = @String + @Delimiter
--Get position of first Comma
set @Pos = charindex(@Delimiter,@String)
set @NextPos = 1
--Loop while there is still a comma in the String of levels
while (@pos <> 0)
begin
-- set @NextString = substring(@String,1,@Pos – 1)
insert into @ValueTable ([Value]) Values (@NextString)
set @String = substring(@String,@pos +1,len(@String))
set @NextPos = @Pos
set @pos = charindex(@Delimiter,@String)
end
return
end
dbo.NameWithCommaa
0 comments Saturday, October 02, 2010 Posted by Vikas SharmaLabels: SQLFunctions
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER FUNCTION [dbo].[NameWithCommaa] (
/*
FUNCTION ListToTable
Usage: select dbo.TableToString('2,13') order by entry desc
PURPOSE: Takes a comma-delimited list as a parameter and returns the values of that list into a table variable.
*/
@mylist varchar(8000)
)
Returns varchar(1000)
as
BEGIN
DECLARE @ListTable TABLE (
seqid int not null,
entry varchar(255) not null)
DECLARE
@this varchar(255),
@rest varchar(8000),
@pos int,
@seqid int
SET @this = ' '
SET @seqid = 1
SET @rest = @mylist
SET @pos = PATINDEX('%,%', @rest)
WHILE (@pos > 0)
BEGIN
set @this=substring(@rest,1,@pos-1)
set @rest=substring(@rest,@pos+1,len(@rest)-@pos)
INSERT INTO @ListTable (seqid,entry) VALUES (@seqid,RTRIM(LTRIM(@this)))
SET @pos= PATINDEX('%,%', @rest)
SET @seqid=@seqid+1
END
set @this=@rest
INSERT INTO @ListTable (seqid,entry) VALUES (@seqid,@this)
-- RETURN
-----------------------------
declare @pages varchar(200)
SELECT @pages = COALESCE(@pages + ', ', '') + convert( varchar(50),Name)FROM
(
select Name from tbl_Rights,
(select entry from listtotable(@mylist)) newtable
where tbl_Rights.ID=cast (newtable.entry as bigint)
) as new
return @pages
END
dbo.TableToString
0 comments Saturday, October 02, 2010 Posted by Vikas SharmaLabels: SQLFunctions
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER FUNCTION [dbo].[TableToString] (
/*
FUNCTION ListToTable
Usage: select dbo.TableToString('2,13') order by entry desc
PURPOSE: Takes a comma-delimited list as a parameter and returns the values of that list into a table variable.
*/
@mylist varchar(8000)
)
Returns varchar(1000)
as
BEGIN
DECLARE @ListTable TABLE (
seqid int not null,
entry varchar(255) not null)
DECLARE
@this varchar(255),
@rest varchar(8000),
@pos int,
@seqid int
SET @this = ' '
SET @seqid = 1
SET @rest = @mylist
SET @pos = PATINDEX('%,%', @rest)
WHILE (@pos > 0)
BEGIN
set @this=substring(@rest,1,@pos-1)
set @rest=substring(@rest,@pos+1,len(@rest)-@pos)
INSERT INTO @ListTable (seqid,entry) VALUES (@seqid,RTRIM(LTRIM(@this)))
SET @pos= PATINDEX('%,%', @rest)
SET @seqid=@seqid+1
END
set @this=@rest
INSERT INTO @ListTable (seqid,entry) VALUES (@seqid,@this)
-- RETURN
-----------------------------
declare @pages varchar(200)
SELECT @pages = COALESCE(@pages + ', ', '') + convert( varchar(50),Category)FROM
(
select Category from tbl_Category,
(select entry from listtotable(@mylist)) newtable
where tbl_Category.ID=cast (newtable.entry as bigint)
) as new
return @pages
END
dbo.ListToTable
0 comments Saturday, October 02, 2010 Posted by Vikas SharmaLabels: SQLFunctions
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER FUNCTION [dbo].[ListToTable] (
/*
FUNCTION ListToTable
Usage: select entry from listtotable('abc,def,ghi') order by entry desc
PURPOSE: Takes a comma-delimited list as a parameter and returns the values of that list into a table variable.
*/
@mylist varchar(8000)
)
RETURNS @ListTable TABLE (
seqid int not null,
entry varchar(255) not null)
AS
BEGIN
DECLARE
@this varchar(255),
@rest varchar(8000),
@pos int,
@seqid int
SET @this = ' '
SET @seqid = 1
SET @rest = isnull(@mylist,'')
SET @pos = PATINDEX('%,%', @rest)
WHILE (@pos > 0)
BEGIN
set @this=substring(@rest,1,@pos-1)
set @rest=substring(@rest,@pos+1,len(@rest)-@pos)
INSERT INTO @ListTable (seqid,entry) VALUES (@seqid,@this)
SET @pos= PATINDEX('%,%', @rest)
SET @seqid=@seqid+1
END
set @this=@rest
INSERT INTO @ListTable (seqid,entry) VALUES (@seqid,@this)
RETURN
END