DotNetfunda |
Monday, July 26, 2010
Sunday, July 18, 2010
Sample Coding
1.To clear history and disabled back button
In Button property set PostbackURL - redirect page URL
in redirected page access
3. To Set the screen based on resolution
call the above function on body tag
ex.. <body onload="javascript:onLoad()">
automatically the browser will be maximized based on your resolution
4. window.opener.document.location.reload(); // Parent window refresh
5. window.document.location.reload(); // current window refresh
6. how to reset Form?
8. window.close(); // current close command
if it doesn't works in firefox browser
please set your firefox browser:
10.decoration = none // to display is none , instead of hidden
11. how to set first letter should be capital letters
string test = "Test StRiNg";
string formatted = System.Globalization.CultureInfo.CurrentUICulture.TextInfo.ToTitleCase(test);
12 . Read Grid Values using Javascript
<script type="text/javascript">
page directive MaintainScrollPositionOnPostback
14. onfocus select the entire text
<asp:TextBox ID="TextBox1" runat="server" Text="1" onfocus="this.select();"></asp:TextBox>
15 . Set Transparent of a image
Control myForm = Page.FindControl("Form1");
22. javascript error "Sys.InvalidOperationException. ScriptLoader.loadscripts cannot be called while the ScriptLoader is already loading scripts".
23. how to access all the controls through javascript
27. Find the broswer version
Response.Cache.SetCacheability(HttpCacheability.NoCache);Javascript
Response.Cache.SetAllowResponseInBrowserHistory(false);
2.how to get previuos page value from another page?<body onload="history.go(1);">
In Button property set PostbackURL - redirect page URL
in redirected page access
TextBox txt = (TextBox)Page.PreviousPage.FindControl("TextBox1");
txt.Text;
3. To Set the screen based on resolution
function onLoad()
{
window.resizeTo(screen.availWidth,screen.availHeight);
}
call the above function on body tag
ex.. <body onload="javascript:onLoad()">
automatically the browser will be maximized based on your resolution
4. window.opener.document.location.reload(); // Parent window refresh
5. window.document.location.reload(); // current window refresh
6. how to reset Form?
<input type="button" value="Reset Form" onClick="this.form.reset()" />7. To display message box from coding
ScriptManager.RegisterClientScriptBlock(this, GetType(), "Success", "window.setTimeout(\"alert('Record(s) successfully updated.');\",0);", true);To display message from server side to invoke the client side script
8. window.close(); // current close command
if it doesn't works in firefox browser
please set your firefox browser:
1.input "about:config " to your firefox address bar and enter;
2.make sure your "dom.allow_scripts_to_close_windows" is true9. how to pass value from2 to form1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2(this);
frm.Show();
}
}
public partial class Form2 : Form
{
Form _frm;
public Form2(Form frm)
{
_frm=frm;
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1 objMain = (Form1)_frm ;
objMain.textBox1.Text = "Hello";
}
}
10.decoration = none // to display is none , instead of hidden
11. how to set first letter should be capital letters
string test = "Test StRiNg";
string formatted = System.Globalization.CultureInfo.CurrentUICulture.TextInfo.ToTitleCase(test);
12 . Read Grid Values using Javascript
<script type="text/javascript">
function showdata()13. How to maintain cusor positon
{
var gridViewCtlId = '<%=GridView1.ClientID%>';
var grid = document.getElementById(gridViewCtlId);
var gridLength = grid.rows.length;
for (var i = 1; i < gridLength; i++)
{
var cols= grid.rows[i].cells.length
for(var j=0; j < cols; j++)
{
cell=grid.rows[i].cells[j];
alert(cell.innerText);
}
}
}
</script>
page directive MaintainScrollPositionOnPostback
14. onfocus select the entire text
<asp:TextBox ID="TextBox1" runat="server" Text="1" onfocus="this.select();"></asp:TextBox>
15 . Set Transparent of a image
<asp:ImageButton style="filter:alpha(opacity=10)" ID="ImageButton1" runat="server" AlternateText="Search" ImageUrl="~/Images/calendar.gif" />16. Add zeroes before number
String.Format("{0:00000}", 15); // "00015"17. Custom number formatting (e.g. phone number)
String.Format("{0:00000}", -15); // "-00015"
Align number to the right or left
string.Format("{0,5}", 15); // " 15"
String.Format("{0,-5}", 15); // "15 "
String.Format("{0,5:000}", 15); // " 015"
String.Format("{0,-5:000}", 15); // "015 "
String.Format("{0:+### ### ### ###}", 447900123456); // "+447 900 123 456"18. Phone No (###) ###-#### validation control
String.Format("{0:##-####-####}", 8958712551); // "89-5871-2551"
<asp:RegularExpressionValidator runat="server" ID="PNRegEx" ControlToValidate="PhoneNumberTextBox" Display="None" ValidationExpression="((\(\d{3}\) ?)19. To find Labels
(\d{3}-))?\d{3}-\d{4}"
ErrorMessage="<b>Invalid Field</b><br />Please enter a phone number in the format:<br />(###) ###-####" />
Control myForm = Page.FindControl("Form1");
foreach (Control ctl in myForm.Controls)20. Check box checking differently
{
if (ctl.GetType().ToString().Equals("System.Web.UI.WebControls.Label"))
{
((Label)ctl).Text = i.ToString();
i++;
}
}
Label1.Text = string.Format("Check box1 status <b>{0}</b> check box2 status <b>{1}</b>",21. If onblur , the textbox show display a message and change the background color
(CheckBox1.Checked ? "do" : "do not"), (CheckBox2.Checked ? "do" : "do not"));
var defaultText ="Enter Your Keyword";
function WaterMark(txt, evt)
{
if(txt.value.length == 0 && evt.type == "blur")
{
txt.style.color = "gray"; --------- ERROR
txt.value = defaultText;
}
if(txt.value == defaultText && evt.type == "focus")
{
txt.style.color = "black";
txt.value="";
}
}
22. javascript error "Sys.InvalidOperationException. ScriptLoader.loadscripts cannot be called while the ScriptLoader is already loading scripts".
<script type="text/javascript">write the above query in a page
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(initRequest);
function initRequest(sender, args)
{
if(Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) args.set_cancel(true);
}
</script>
23. how to access all the controls through javascript
24. how to get id of the particular control
var elem = document.getElementById('frmMain').elements;
for(var i = 0; i < elem.length; i++)
{
str += "<b>Type:</b>" + elem[i].type + " ";
str += "<b>Name:</b>" + elem[i].name + " ";
str += "<b>Value:</b><i>" + elem[i].value + "</i> ";
str += "<BR>";
}
var ctrl1 = document.getElementsByTagName('textarea');25. Delete duplicate records in a table
for (var i = 0; i < ctrl1.length; i++)
{
if (ctrl1[i].title == 'Order')
{
ctrl1[i].value = ordno;
}
}
}
WITH CTE (COl1,Col2, DuplicateCount)26. How to get readonly textbox value in server side
AS
(
SELECT COl1,Col2,
ROW_NUMBER() OVER(PARTITION BY COl1,Col2 ORDER BY Col1) AS DuplicateCount
FROM DuplicateRcordTable
)
DELETE
FROM CTE
WHERE DuplicateCount > 1
Textbox1.Attributes.Add("readonly", "readonly");
27. Find the broswer version
Dim browserCaps As HttpBrowserCapabilities = Page.Request.Browser
lblbrowser.Text = "Your Browser : " + browserCaps.Browser + " Version : " + browserCaps.MajorVersion.ToString
28. how to change message box font ?
http://msdn.microsoft.com/en-gb/magazine/cc188920.aspx
29. Autocomplete Extender Method using DB
[WebMethod]
public string[] GetCountryInfo(string prefixText)
{
int count = 10;
string sql = "Select * from Country Where Country_Name like @prefixText";
SqlDataAdapter da = new SqlDataAdapter(sql,”Your Connection String Comes Here”));
da.SelectCommand.Parameters.Add("@prefixText", SqlDbType.VarChar, 50).Value = prefixText+ "%";
DataTable dt = new DataTable();
da.Fill(dt);
string[] items = new string[dt.Rows.Count];
int i = 0;
foreach (DataRow dr in dt.Rows)
{
items.SetValue(dr["Country_Name"].ToString(),i);
i++;
}
return items;
}
<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" MinimumPrefixLength="1" ServiceMethod="GetCountryInfo" ServicePath="WebService.asmx" TargetControlID="TextBox1"> </cc1:AutoCompleteExtender>
30. Pass Values from one page to another page without State Manangement techniques.
use Cross-page posting, Posts current page information to the target page.
instead of redirect , use button property postbackURL =target page
ex..
<asp:Button ID="Button1" PostBackUrl="~/TargetPage.aspx" runat="server" Text="Submit" />
in TargetPage Onload
if (Page.PreviousPage != null)
{
DropDownList SourceTextBox = (DropDownList )Page.PreviousPage.FindControl("DropDownList1");
if (SourceTextBox != null)
{
Label1.Text = SourceTextBox.SelectedValue;
}
}
31. How to change SA password in SQL Server
LOGIN sa ENABLE
GO
ALTER LOGIN sa WITH PASSWORD = '<password>'
GO
32. for CSS calls in windows application
<Global.System.Configuration.DefaultSettingValue("Font: Name=Arial, Size=9")> Public Property Font() As String
Get
Return CType(strFont, String)
End Get
Set(ByVal value As String)
strFont = value
End Set
End Property
33. Display hand symbol in div or button
<div style="cursor:hand"><u>submit</u></div>
34. Rectangle textbox to ellipse
GraphicsPath gp = new GraphicsPath();
gp.AddEllipse(0, 0, this.cmdbtn.ClientSize.Width,this.cmdbtn.ClientSize.Height);
this.cmdbtn.Region = new Region(gp);
35. save screen of the windows application
int width, height;
width = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Width;
height = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Height;
The following code will capture the screen and save it in the desktop as image.bmp;
Bitmap sBit;
Rectangle screenRegiion = Screen.AllScreens[0].Bounds;
sBit = new Bitmap(width, height, PixelFormat.Format32bppArgb);
Graphics sGraph = Graphics.FromImage(sBit);
sGraph.CopyFromScreen(screenRegiion.Left, screenRegiion.Top, 0, 0, screenRegiion.Size);
string savedPath =Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\exmpale.bmp";
sBit.Save(savedPath);
36. To bind the combo box after particulare time interval
//Define a delgate to bind a combobox
delegate void BindComboBox();
//Defien a timer to bind the combobox for regular intervals
System.Timers.Timer bindTimer = new System.Timers.Timer();
//on form load add a event to elapsed.
bindTimer.Elapsed += new ElapsedEventHandler(BindComboBoxEvent);
bindTimer.Interval = 60000;//for every one minute
bindTimer.Start();
public void BindComboBoxEvent(object source, ElapsedEventArgs e)
{
//Create a Object for delagate and pass the bidn data method as argument
BindComboBox bind= new BindComboBox(BindData);
this.BeginInvoke(bind);
}
private void BindData()
{
//Write code to bind data to combo box }
37. #Region "ShowReport"
Public Function ShowReport(ByVal path As String, ByVal sParamFld As String, ByVal sParamVal As String, ByVal sReportViewer As CrystalDecisions.Web.CrystalReportViewer) As ReportDocument
Dim tmpSortList As New SortedList
Dim ParamLength As Int16 = 0, iLoop As Int16 = 0
Dim ParamFld() As String, ParamFldVal() As String
Try
myReportDocument = New ReportDocument
myReportDocument.Load(path)
myReportDocument.SetDatabaseLogon(user, pwd, Servername, Database)
Dim Logoninfo As New TableLogOnInfo()
Logoninfo.ConnectionInfo.ServerName = Servername
Logoninfo.ConnectionInfo.DatabaseName = Database
Logoninfo.ConnectionInfo.UserID = user
Logoninfo.ConnectionInfo.Password = pwd
'myReportDocument.Database.Tables().Item(0).TestConnectivity()
myReportDocument.Database.Tables().Item(0).ApplyLogOnInfo(Logoninfo)
myReportDocument.VerifyDatabase()
ParamFld = sParamFld.Split("*")
ParamFldVal = sParamVal.Split("*")
If ParamFld.Length <> ParamFldVal.Length Then
Err.Raise(1, , "Parameter Fleid should be equal to Parameter Value")
End If
For iLoop = 0 To UBound(ParamFld)
tmpSortList.Add(ParamFld(iLoop), ParamFldVal(iLoop))
Next
ParamFldDefn = myReportDocument.DataDefinition.ParameterFields
ParamFldDefn.Reset()
Dim tmpCount As Integer = 0
sReportViewer.ReportSource = myReportDocument
'sReportViewer.DataBind()
sReportViewer.EnableParameterPrompt = False
For tmpCount = 0 To tmpSortList.Count - 1
myReportDocument.SetParameterValue(ParamFldDefn(tmpCount).Name, tmpSortList(ParamFldDefn(tmpCount).Name).ToString())
Next
Return myReportDocument
'fnToolbarSetting()
Catch ex As Exception
' lblErr.Text = ex.Message
Return Nothing
End Try
End Function
#End Region
38. convert string
Public Function ConvertoDate(ByVal dateString As String, ByRef result As DateTime) As DateTime
Try
Dim supportedFormats() As String = New String() {"dd/MM/yyyy", "MM/dd/yyyy", "MM/dd/yy", "ddMMMyyyy", "dMMMyyyy"}
result = DateTime.ParseExact(dateString, supportedFormats, System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None)
Return result
Catch ex As Exception
Return Nothing
End Try
End Function
39. redirect to prevoius page
Response.Redirect(Request.UrlReferrer.ToString(),false);
40 . Now entered value from SQL
insert into dupemp(name,salary,deptno) values('1sd',4000,12)
with CTE as(select *,ROW_NUMBER() over(order by (select 0))as row from dupemp)
select * from cte where row=(select max(row) from cte)
method 2
select top 1 column_list FROM
(select ROW_NUMBER() over(order by (select 0)) as rownum,column_list from table_name) t order by rownum desc
BEGIN DECLARE @Output VARCHAR(8000) SELECT @Output = COALESCE (@Output + ';', '') + CONVERT(varchar(20), PolicyNo)
FROM tblSubmissionList END
42. To password encription
FormsAuthentication.HashPasswordForStoringInConfigFile(objCreateUser.Pwd, "MD5");
43. to use Session in class file
HttpContext.Current.Session["UserName"]
44. How to use ModalPopupExtender for the asking the requirement and process within the same page
(ex.. like javascript prompt , msgbox like that)
1. Create the panel with the required information
ex. forgot password
<asp:Panel ID="pnlForgotPwd" runat="server" BorderWidth="3" BorderStyle="Double" BorderColor="Gray" CssClass="cssImg">
<asp:Panel ID="handlePwd" runat="server" Style="cursor: move; background-color: #F5F5F5;
border: solid 1px Gray; color: Black;">
<div>
<b style="color: #B5AA6D"> Forgot your password.</b>
</div>
</asp:Panel>
<asp:UpdatePanel ID="upForgotPwd" runat="server">
<ContentTemplate>
<table align="center" style="margin-left: 10px; margin-right: 10px;">
<tr>
<td align="right" style="height: 30px;">
Login ID :
</td>
<td align="right" valign="middle">
<asp:TextBox ID="txtLoginID" runat="server" Width="170px" ValidationGroup="ForgotPwd"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="rfvLoginID" runat="server" ControlToValidate="txtLoginID"
Font-Size="Small" ValidationGroup="ForgotPwd">*</asp:RequiredFieldValidator>
</td>
<td>
<asp:UpdateProgress ID="udProgressPwd" runat="server" AssociatedUpdatePanelID="upForgotPwdBtn"
DisplayAfter="50" DynamicLayout="true">
<ProgressTemplate>
<div style="margin-left: 15px;">
<asp:Image ID="imgProPwd" runat="server" Height="15px" ImageUrl="~/images/Processing2.gif" /></div>
</ProgressTemplate>
</asp:UpdateProgress>
</td>
</tr>
<tr>
<td colspan="4">
<hr />
</td>
</tr>
<tr align="center">
<td align="center" colspan="2" valign="bottom">
<asp:UpdatePanel ID="upForgotPwdBtn" runat="server">
<ContentTemplate>
<asp:ImageButton ID="btnForgotPassword" ImageUrl="~/images/submit1.png" runat="server"
ValidationGroup="ForgotPwd" OnClick="btnForgotPassword_Click" />
<asp:ImageButton ID="btnCancelPwd" ImageUrl="~/images/cancel.png" runat="server"
CausesValidation="false" OnClick="btnCancelPwd_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
2. when the modelextender will arise
<asp:LinkButton ID="btnForgotPwd" runat="server" ForeColor="#B5AA6D" Text="Forgot Password" />
3. Assign ModalPopupExtender
<cc1:ModalPopupExtender ID="btnForgotPwd_ModalPopupExtender" BackgroundCssClass="BGCSS"
runat="server" DynamicServicePath="" Enabled="True" TargetControlID="btnForgotPwd"
PopupControlID="pnlForgotPwd" PopupDragHandleControlID="handleForgotPwd" CancelControlID="btnCancel">
</cc1:ModalPopupExtender>
TargetControlID - to invoke the modalpopupextender
PopupControlID - panel Control id
PopupDragHandleeControlId = which part to drag
CancelControlId - to canel the modalpopupextender
4. Cancel button event
pnlForgotPwd.Style.Add("display", "none");
btnForgotPwd_ModalPopupExtender.Hide();
txtLoginID.Text = "";
upMain.Update();
5. How to show error while popupwindow
a) create one more panel with required control to display error message
<div id="MsgBox" runat="server">
</div>
<asp:Panel ID="pnlOuterMsgBox" runat="server" CssClass="outerPopup" Style="display: none;">
<asp:Panel ID="pnlInnerMsgBox" BackColor="#F0F0F0" CssClass="cssImg" runat="server"
Width="350px">
<br />
<asp:Image ID="imgMsgBox" runat="server" /><asp:Label ID="lblMsgBox" runat="server"></asp:Label>
<br />
<br />
<asp:ImageButton ID="btnOK" runat="server" ImageUrl="~/images/ok.png" />
<br />
</asp:Panel>
</asp:Panel>
b) create one more modalpopextender
<cc1:ModalPopupExtender ID="mpeMsgBox" runat="server" TargetControlID="MsgBox" PopupControlID="pnlOuterMsgBox"
CancelControlID="btnCancel" OkControlID="btnOK" BackgroundCssClass="BGCSS" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel" Enabled="false" />
success and not success
if (objUser.CheckUserExists(txtLoginID.Text))
{
lblMsgBox.ForeColor = System.Drawing.Color.Green;
imgMsgBox.ImageUrl = "~/images/id_ok.png";
lblMsgBox.Text = " Password successfully send to your HP Number.";
txtLoginID.Text = "";
mpeMsgBox.Show();
pnlForgotPwd.Style.Add("display", "none");
btnForgotPwd_ModalPopupExtender.Hide();
upMain.Update();
}
else
{
lblMsgBox.ForeColor = System.Drawing.Color.Red;
imgMsgBox.ImageUrl = "~/images/id_occ.png";
lblMsgBox.Text = " Incorrect Login ID.";
mpeMsgBox.Show();
pnlForgotPwd.Visible = true;
btnForgotPwd_ModalPopupExtender.Show();
upMain.Update();
}
45. to focus popupwindow
function openPopup(purl)
{
wndAttr = "width=520,height=630,left=100,top=100";
var w = window.open(purl, 'popup_test', wndAttr);
w.focus();
}
46. retrieve page records
command.ExecutePageReader(CommandBehavior.Default, 1, 10);
47. REfresh every 2 seconds
<body onload="doTimer();"> <form id="form1" runat="server" > <div> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:GridView ID="GridView1" runat="server"> </asp:GridView> </ContentTemplate> </asp:UpdatePanel> </div> </form> <script type="text/javascript"> var t; var timer_is_on = 0; function timedCount() { __doPostBack("UpdatePanel1", ""); t = setTimeout("timedCount()", 2000);//2 second } function doTimer() { if (!timer_is_on) { timer_is_on = 1; timedCount();} }</script> </body>
48.. Gridview Chkbox in ASp Update panel
function CheckAllElements(checkallbox) {
if (checkallbox.checked == true) {
for (i = 0; i < document.forms[0].elements.length; i++) {
//.match("world")
if (document.forms[0].elements[i].id.match("chkDetails") != null)
{
if (document.forms[0].elements[i].type == 'checkbox') {
document.forms[0].elements[i].checked = true;
}
}
}
}
else {
for (i = 0; i < document.forms[0].elements.length; i++) {
if (document.forms[0].elements[i].id.match("chkDetails") != null) {
if (document.forms[0].elements[i].type == 'checkbox') {
document.forms[0].elements[i].checked = false;
}
}
}
}
//document.Form1.submit();
}
49. convert linq to datatable
public DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
{
DataTable dtReturn = new DataTable();
// column names
PropertyInfo[] oProps = null;
if (varlist == null) return dtReturn;
foreach (T rec in varlist)
{
// Use reflection to get property names, to create table, Only first time, others
//will follow
if (oProps == null)
{
oProps = ((Type)rec.GetType()).GetProperties();
foreach (PropertyInfo pi in oProps)
{
Type colType = pi.PropertyType;
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
colType = colType.GetGenericArguments()[0];
dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
}
DataRow dr = dtReturn.NewRow();
foreach (PropertyInfo pi in oProps)
{
dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue
(rec, null);
}
dtReturn.Rows.Add(dr);
}
return dtReturn;
}
LINQToDataTable(ResultMenuAcc); // var ResultMenuAcc result
50. to enter key active login id
txtPassword.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13) __doPostBack('" + btnLogin.UniqueID + "','')");
52. Split only number from string exx. adsfad1234
you can use regular expression to split the value
ex.
string val ="SCV 5000";
Regex r = new Regex("^[0-9]$");
string[] tmpval = r.Split(val);
tmpval[1] = have numberic values
tmpval[0] = character values
Regex not work try below one "^\d+$"
53. SCrolling text from bottom to up with scroll bar
<marquee direction=up height=150 scrollAmount=2.8 scrollDelay=70 onMouseDown="this.stop()" onMouseOver="this.stop()" onMouseMove="this.stop()" onMouseOut="this.start()"> hello <br /> hello1 </marquee>
54. Remove duplicates in a string
function removeDuplicates(field) {
var temp = field.value;
var array = temp.split(" ");
array.sort();
temp = array.join(" ");
55. Without prompting close button message
function CloseWindow()
{
window.open('','_self','');
window.close();
}
56.. Refresh page
<asp:Timer ID="Timer1" OnTick="Timer1_Tick" runat="server" Interval="10000" />
<asp:UpdatePanel ID="StockPricePanel" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" />
</Triggers>
<ContentTemplate>
Stock price is <asp:Label id="StockPrice" runat="server"></asp:Label><BR />
as of <asp:Label id="TimeOfPrice" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
protected void Timer1_Tick(object sender, EventArgs e)
{
}
57. to populate the file and folder in tree
public void PopulateTree(string dir, TreeNode node) {
// get the information of the directory
DirectoryInfo directory = new DirectoryInfo(dir);
// loop through each subdirectory
foreach(DirectoryInfo d in directory.GetDirectories()) {
// create a new node
TreeNode t = new TreeNode(d.Name);
// populate the new node recursively
PopulateTree(d.FullName, t);
node.Nodes.Add(t); // add the node to the "master" node
}
// lastly, loop through each file in the directory, and add these as nodes
foreach(FileInfo f in directory.GetFiles()) {
// create a new node
TreeNode t = new TreeNode(f.Name);
// add it to the "master"
node.Nodes.Add(t);
}
}
58. Common on Text box CSS
input[type=text] {
width: 300px;
background-color: cyan;
}
59.custom MessageBox
private void MessageBox(string Message)
{ Guid Key = Guid.NewGuid();
string K = Key.ToString().Replace("-", "");
ScriptManager.RegisterClientScriptBlock(this, GetType(), k, "alert('" + Message + "');", true); }
Dyamically set User Name , Password for crystal report.
myReportDocument.SetDatabaseLogon(user, pwd, Servername, Database)
Dim Logoninfo As New TableLogOnInfo()
Logoninfo.ConnectionInfo.ServerName = Servername
Logoninfo.ConnectionInfo.DatabaseName = Database
Logoninfo.ConnectionInfo.UserID = user
Logoninfo.ConnectionInfo.Password = pwd
myReportDocument.Database.Tables().Item(0).ApplyLogOnInfo(Logoninfo)
myReportDocument.VerifyDatabase()
Dim Logoninfo As New TableLogOnInfo()
Logoninfo.ConnectionInfo.ServerName = Servername
Logoninfo.ConnectionInfo.DatabaseName = Database
Logoninfo.ConnectionInfo.UserID = user
Logoninfo.ConnectionInfo.Password = pwd
myReportDocument.Database.Tables().Item(0).ApplyLogOnInfo(Logoninfo)
myReportDocument.VerifyDatabase()
Subscribe to:
Posts (Atom)