Pages

Monday, April 25, 2011

Gridview Checkbox Header

0 comments




<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkSelectAll" runat="server" AutoPostBack="true" OnCheckedChanged="chkSelectAll_CheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="true" OnCheckedChanged="chkSelect_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
-------------------------------------------------
HEADER CHECKBOX EVENT
-------------------------------------------------
protected void chkSelectAll_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkAll = (CheckBox)GridView1.HeaderRow.FindControl("chkSelectAll");
if (chkAll.Checked == true)
{
foreach (GridViewRow gvRow in GridView1.Rows)
{
CheckBox chkSel =
(CheckBox)gvRow.FindControl("chkSelect");
chkSel.Checked = true;
}
}
else
{
foreach (GridViewRow gvRow in GridView1.Rows)
{
CheckBox chkSel = (CheckBox)gvRow.FindControl("chkSelect");
chkSel.Checked = false;
}
}
}

-----------------------------------------------------------
ITEM CHECKBOX EVENT
------------------------------------------------------------
protected void chkSelect_CheckedChanged(object sender, EventArgs e)
{
int count = 0;
int totalChkBoxes = 0;
foreach (GridViewRow gvRow in GridView1.Rows)
{
totalChkBoxes += 1;
CheckBox chkSel = (CheckBox)gvRow.FindControl("chkSelect");

if (chkSel.Checked == true)
{
count += 1;
}
}

if (count == 0) // if no checkbox is selected then make header checkbox false.
{
CheckBox chkAll = (CheckBox)GridView1.HeaderRow.FindControl("chkSelectAll");
chkAll.Checked = false;
}

count = count + 1;
if (count == totalChkBoxes + 1)
{
CheckBox chkAll = (CheckBox)GridView1.HeaderRow.FindControl("chkSelectAll");
chkAll.Checked = true;
}

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



Sunday, April 24, 2011

Misc. Snippets

0 comments

fdfadsf
test snippet

Only Numbers in Txtbox

0 comments


function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
---------------------------
<asp:TextBox ID="txtph2" MaxLength="3"
onkeypress="return isNumberKey(event)"
runat="server"></asp:TextBox>

Auto_TAB

0 comments

............AutoTab.js------------------
------------------------------------------------------------
-- make this a separate .js file and add reference in head section of page.
------------------------------------------------------------
/* This script and many more are available free online at
The JavaScript Source!! http://javascript.internet.com
*/
var isNN = (navigator.appName.indexOf("Netscape") != -1);

function autoTab(input, len, e) {
var keyCode = (isNN) ? e.which : e.keyCode;
var filter = (isNN) ? [0, 8, 9] : [0, 8, 9, 16, 17, 18, 37, 38, 39, 40, 46];
if (input.value.length >= len && !containsElement(filter, keyCode)) {
input.value = input.value.slice(0, len);
input.form[(getIndex(input) + 1) % input.form.length].focus();
}

function containsElement(arr, ele) {
var found = false, index = 0;
while (!found && index < arr.length)
if (arr[index] == ele)
found = true;
else
index++;
return found;
}

function getIndex(input) {
var index = -1, i = 0, found = false;
while (i < input.form.length && index == -1)
if (input.form[i] == input) index = i;
else i++;
return index;
}
return true;
}
----------------------------------------------------------------------
<script type="text/javascript" src="JS/autoTab.js"></script>

<asp:TextBox ID="txtph2" MaxLength="3"
onKeyUp="return autoTab(this, 3, event);"
onkeypress="return isNumberKey(event)"
runat="server"></asp:TextBox>


SQL Random List Of Records

0 comments


-----------------------------------------------------------------
SQL RANDOM LIST OF PRODUCTS

Select Top 10 *
from
(
Select ProductID, ProductName, UnitPrice
from Products
--Where
-- ForumQuestion.QuestionTitle Like @SearchKeyword
) MyTable
ORDER BY NEWID()



Get_Random_Password

0 comments


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

public static string GetRandomPassword(int length)
{
char[] chars = "$%#@!*abcdefghijklmnopqrstuvwxyz1234567890?;:ABCDEFGHIJKLMNOPQRSTUVWXYZ^&".ToCharArray();
string password = string.Empty;
Random random = new Random();

for (int i = 0; i < length; i++)
{
int x = random.Next(1,chars.Length);
//Don't Allow Repetation of Characters
if (!password.Contains(chars.GetValue(x).ToString()))
password += chars.GetValue(x);
else
i--;
}
return password;
}

Its a simple logic instead by generating a random number between 1 and Length of characters. It also checks that same character is not repeated in generated password and finally return the randomly generated password string of desired length.

Gridview_Tips_n_Tricks

0 comments


------------------------------------------------------------
void GridView1_RowUpdated(Object sender, GridViewUpdatedEventArgs e)

{

// Retrieve the row being edited.

int index = GridView1.EditIndex;

GridViewRow row = GridView1.Rows[index];


// Retrieve the value of the first cell

lblMsg.Text = "Updated record " + row.Cells[1].Text;

}


Row_Deleting Event

0 comments

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


protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)

{

int ID = (int)GridView1.DataKeys[e.RowIndex].Value;

// Query the database and get the values based on the ID

}

Saturday, April 23, 2011

LinkButtons

0 comments


--------------------------------------------------------
<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>
//(can also use <img src> in linkbutton)

lnk = ((LinkButton)(sender));
string[] array = lnk.CommandArgument.ToString().Split(',');
prjID = Convert.ToInt32(array[1].ToString());
Int32 bid = Convert.ToInt32(array[0].ToString());

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




Row_Updated Event

0 comments


void GridView1_RowUpdated(Object sender, GridViewUpdatedEventArgs e)
{

// Retrieve the row being edited.

int index = GridView1.EditIndex;

GridViewRow row = GridView1.Rows[index];


// Retrieve the value of the first cell

lblMsg.Text = "Updated record " + row.Cells[1].Text;

}


gridview_rowEditing

0 comments


-------------------------------------------------------------
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();

GridViewRow grow = (GridViewRow)GridView1.Rows[e.NewEditIndex];
DropDownList ddlR = new DropDownList();
ddlR = (DropDownList)grow.FindControl("ddlrole");

DropDownList ddlC = (DropDownList)grow.FindControl("ddlcnt");

if (ddlR != null)
{
ddlR.DataSource = GetRoles();
ddlR.DataTextField = "role";
ddlR.DataValueField = "ID";
ddlR.DataBind();

}
string r = ViewState["role"].ToString();
ddlR.Items.FindByText(r).Selected = true;


if (ddlC != null)
{
ddlC.DataSource = GetCountry();
ddlC.DataTextField = "countryname";
ddlC.DataValueField = "countryid";
ddlC.DataBind();

}
string c = ViewState["cnt"].ToString();
ddlC.Items.FindByText(c).Selected = true;
}





URL Functions

0 comments


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

public string getImageUrl(bool act)
{
string imageurl = "";
string path = "~/images/";
if (act == true)
{
imageurl = path + "available.png";
return imageurl;
}
else
{
imageurl = path + "notav.png";
return imageurl;
}
}
------------------------------------------------------
<ItemTemplate>
<asp:ImageButton ID="imgBtnStatus" CommandName="changestatus"
CommandArgument='<%#Eval("userid")%>'
ToolTip="Click to change status. !!!"
ImageUrl='<%#getImageUrl(Convert.ToBoolean((Eval("IsActive"))))%>'
runat="server" />
<asp:HiddenField ID="HiddenField1" Value='<%#Eval("IsActive")%>'
runat="server" />
</ItemTemplate>
---------------------------------------------------------------------------------------------------------------









change status images 2

0 comments


-------------------------------------------------------------------
----------------------------------
alter proc usp_Change_Status
(
@userid int,
@status varchar(50)
)
as
update tbl_user set IsActive=@status where userid=@userid

-----------------------------------------------------
public string getImageUrl(bool act)
{
string imageurl = "";
string path = "~/images/";
if (act == true)
{
imageurl = path + "available.png";
return imageurl;
}
else
{
imageurl = path + "notav.png";
return imageurl;
}
}



-------------------------------------------------------------------------------------------
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="imgBtnStatus" CommandName="changestatus"
CommandArgument='<%#Eval("userid")%>'
ToolTip="Click to change status. !!!"

ImageUrl='<%#getImageUrl(Convert.ToBoolean((Eval("IsActive"))))%>'
runat="server" />

<asp:HiddenField ID="HiddenField1" Value='<%#Eval("IsActive")%>'
runat="server" />
/ItemTemplate>
</asp:TemplateField>

------------------------------------------------------------------------------------------------
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{

if (e.CommandName.ToString() == "changestatus")
{
GridViewRow grow = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;
ImageButton img = e.CommandSource as ImageButton;
GridViewRow gvRow = img.Parent.Parent as GridViewRow;

int id = int.Parse(e.CommandArgument.ToString());

HiddenField hdnField = (HiddenField)GridView1.Rows[gvRow.RowIndex].FindControl("HiddenField1");

string status = "";
if (hdnField.Value == "True")
{
status = "False";
}
else if (hdnField.Value == "False")
{
status = "True";
}

Hashtable ht = new Hashtable();
ht.Add("@userid", id);
ht.Add("@status", status);

NSBuilder.DataAccess.ExecuteNonQuery("usp_Change_Status", ht);
BindGrid();
}

}






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");
}



 

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