1、在页面加aps的label控件,然后在后台给它赋值,再在前台用document.getElementByID('').value获取其text值的方法是错误的,因为label控件编译后就一堆字符串,没有值。要想达到目的,可以使用HiddenField来实现。
2、button.Attributes.Add("onclick", "js函数"),这种方法需要点击两次按钮才能触发js函数。
3、后台向前台的js函数传值
using Ajax
Utility.RegisterTypeForAjax(typeof(部分类名:ZBManage_ZDZBPlan));
public partial class ZBManage_ZDZBPlan :BasePage
{
[AjaxMethod()]
public string 函数名(参数1,参数2,。。。)
{
string str ="";
代码。。。。
resturn str;
//这里不能有页面控件,否则代码将不被执行
}
}
<input id="Button2" type="button" value="。。。" οnclick="var year = document.getElementById('hf_Year').value;var month =document.getElementById('hf_Month').value;var str = ZBManage_ZDZBPlan.函数名(year,month).value;Js函数名(str);" />
4、动态绑定gridview时记得将 AutoGenerateColumns设为true.
5、打印部分页
1)在aspx页标记<div id="printdiv">打印部分</div>
2)<script languang="javascript">
printhtml(printdiv)
{
if(confirm('确定打印吗?'))
{
if(window.print)
{
var div =document.createElement("div");
div.innerHTML = document.body.innerHTML;
var tmp = printdiv.toString();
document.body.innerHTML = tmp;
window.print();
document.body.innerHTML = div.innerHTML;
}
}
}
</script>
3)<input type="button" id="btn" οnclick=“printhtml(document.all.printdiv.innerHTML)” />
5、sql中单引号用兩個 '表示: ' ' 如select * from a where k as ' ' 'a ' ' '
6、对于不确定长度的数组可以使用变长数组ArrayList或者是泛型List<T>
7、页面不转行效果设置:
1)在最外层设<div>并把长宽定死
2)给表格的行加nowrap属性
8、ListBox、Table、DropDownList中的删除,若用循环删除多项,则可能引发错误。因为没删除一项,items就会减少一个,相应的索引就会改变。解决发放就是,从尾部开始循环。如下:
for (int i = listbox.Items.Count-1; i >=0; i--)
{
for (int j = 0; j < dt2.Rows.Count; j++)
{
if (listbox.Items[i].Value == dt2.Rows[j]["Nature"].ToString())
{
listbox.Items.Remove(listbox.Items[i]);
break;
}
}
}
9、通过编程对sharepoint的操作只能在moss服务器端。
10、定义扩展方法需要注意,只能在静态类中定义并且是静态方法,如果扩展方法名和原有方法名发生冲突,那么扩展方法将失效。
11、DownloadFileAsync在下载失败时的确会抛出WebException异常,但是用try...catch是捕获不到这个异常的,这个异常由.NET自动传给了DownloadFileCompleted事件里的AsyncCompletedEventArgs参数e,由e.error获得这个异常。
void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(e.Error.Message); //正常捕获
}
}
12、hh:mm:ss无法显示pm时间,HH:mm:ss可以
如:16:28:30
hh:mm:ss 04:28:30
HH:mm:ss 16:28:30
13、double类型小数后保留两位
double d=12.2121;
string str = d.ToString("F2");
14、如果想在彈出另一個 窗体時 令到用戶不能按別的 窗体可以嘗試使用 窗体.ShowDialog()來彈出子窗体
15、调用浏览器打开网页
![](http://blog.51cto.com/images/editer/InBlock.gif)
![](http://blog.51cto.com/images/editer/InBlock.gif)
![](http://blog.51cto.com/images/editer/InBlock.gif)
![](http://blog.51cto.com/images/editer/InBlock.gif)
Dictionary<string, int> list = new Dictionary<string, int>();
list.Add("d", 1);
//3.0以上版本
foreach (var item in list)
{
Console.WriteLine(item.Key + item.Value);
}
//KeyValuePair<T,K>
foreach (KeyValuePair<string, int> kv in list)
{
Console.WriteLine(kv.Key + kv.Value);
}
//通过键的凑集取
foreach (string key in list.Keys)
{
Console.WriteLine(key + list[key]);
}
//直接取值
foreach (int val in list.Values)
{
Console.WriteLine(val);
}
//非要采取for的办法也可
List<string> test = new List<string>(list.Keys);
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine(test[i] + list[test[i]]);
}
21、WebBrowser控件禁用超链接转向、脚本错误提示、默认右键菜单和快捷键
22、WebBrowser control doesn't have such property to set to enable or disable javascript. If you want to enable/disable javascript, you can enable/disable it in your Internet Security option in the Windows system. That option can be found as below:
Control Panel -> Internet Options -> Security
23、datagridview随内容自适应大小
this.dgvList.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells;
this.dgvList.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.DisplayedCells;
24、txt文件导入SQL Server数据库
BULK INSERT test FROM 'D:\111.txt' WITH
( FIELDTERMINATOR =',',ROWTERMINATOR='\n')
25、SQL Server数据库操作:从一张表插入数据到另一张表
insert into ThunderTask (AttachUrl)select url from test
26、跨线程访问出错:
27、将插入的新行放入datagridview第一行
dataGridView1.Rows.Add(dataRow);
改成:
dataGridView1.Rows.Insert(0,dataRow);
28、datagridview滚动条随选中自动滚动
dataGridView1.Rows[index].Selected = true; // 设置为选中.(index为选重的记录索引)
dataGridView1.FirstDisplayedScrollingRowIndex = index; // 设置在当前区域的第一行显示
29、设置ToolStripMenuItem(button)的快捷键
this.查找FToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.F)));
30、获取扩展名Path.GetExtension(filePath)
31、Windows 服务
1)添加服务:installutil xx.exe
卸载服务:installutil /u xx.exe
2)在服务程序的是设计窗体中,点击右键“添加安装程序”,添加服务安装程序。否则,安装时会出现如下
错误:
正在安装程序集“C:/Program/xx.exe”。
受影响的参数是:
logtoconsole =
assemblypath = C:/Program/xx/xx.exe
logfile = C:/Program/xx.InstallLog
没有 RunInstallerAttribute.Yes 的公共安装程序。在 C:/Program/xx.exe 程序集中可能可以找到
“Yes”属性。
正在提交程序集“C:/Program/xx.exe”。
受影响的参数是:
logtoconsole =
assemblypath = C:/Program/xx.exe
logfile = C:/Program/xx.InstallLog
没有 RunInstallerAttribute.Yes 的公共安装程序。在 C:/Program/xx.exe 程序集中可能可以找到
“Yes”属性。
3) 将serviceProcessInstaller1->Accout属性,设为:LocalSystem(默认是User)。
否则将会出现如下错误:
windows服务安装时,出错:System.ComponentModel.Win32Exception: 帐户名无效或不存在,或者密码对
于指定的帐户
4) 服务启动时报错:没有及时响应启动或控制请求
OnStart里面要放一个运行时间很短的方法,能够成功启动该服务,当OnStart里面放一个运行时间很长的方法(比如超过2小时的方法)时就出现上面那个错误。解决方法是用线程。
You can use wordconv.exe which is part of the Office Compatibility Pack to convert from doc to docx.
Just call the command like so: "C:\Program Files\Microsoft Office\Office12\wordconv.exe" -oice -nme InputFile OutputFile
I'm not sure if you need word installed for it to run but it does work. I use it locally as a windows shell command to convert old office files to 2007 format whenever I want.
33、杀进程
public static void Kill(Application _eApp)
{
IntPtr t = new IntPtr(_eApp.Hwnd);
int k = 0;
GetWindowThreadProcessId(t, out k); //得到本进程唯一标志k
System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k); //得到对进程k的引用
p.Kill(); //关闭进程k
}
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
34、dll引用如何保留注释:将注释生成XML拷到引用目录下
35、当控件被数据绑定时,无法以编程方式向 DataGridView 的行集合中添加行
((DataTable)dataGridView1.DataSource).Rows.Add();
给已绑定的datagridview添加新列
dataGridView1.Columns.Add(new DataGridViewTextBoxColumn());
36、DataGridView标题设置颜色
dataGridView1.EnableHeadersVisualStyles = false;
dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Yellow;
行标题序号
protected override void OnCellFormatting(DataGridViewCellFormattingEventArgs e)
{
DataGridViewRow CurrentRow = this.Rows[e.RowIndex];
CurrentRow.HeaderCell.Value = Convert.ToString(e.RowIndex + 1);
base.OnCellFormatting(e);
}
单元格的边框线的颜色可以通过 DataGridView.GridColor 属性来设定的
37、Regex带委托
HtmlContentCode = Regex.Replace(HtmlContentCode, @"(?is)(\d{4})年(\d{1,2})月([下|上])半月",SubParseTools.GetDate);
static string GetDate(Match mc)
{
if (Regex.IsMatch(mc.Groups[3].Value, "上"))
return (Normal.ParseDateTime(mc.Groups[1] + "/" + mc.Groups[2] + "/" + "01").ToString("yyyy-MM-dd"));
else
return (Normal.ParseDateTime(mc.Groups[1] + "/" + mc.Groups[2] + "/" + "15").ToString("yyyy-MM-dd"));
}
38、volatile
The volatile keyword indicates that a field can be modified in the program by something such as the Operating System, the hardware, or a concurrently executing thread. The system always reads the current value of a volatile object at the point it is requested, even if the previous instruction asked for a value from the same object. Also, the value of the object is written immediately on assignment. The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access. Using the volatile modifier ensures that a thread retrieves the most up-to-date value written by another thread.
39、带参数的线程
private Thread worker;
worker = new Thread(new ParameterizedThreadStart(DoWork));
worker.Start(primeNumberLoopToFind);
private void DoWork(object data) { long primeNumberLoopToFind = (long)data;
。。。。。。。。。。。。。。。。。
}
40、解决交叉线程方法
原理:
1、Gets a value indicating whether the caller must call an Invoke method when making method calls to the control because the caller is on a different thread than the one the control was created on.
Controls in Windows Forms are bound to a specific thread and are not thread safe. Therefore, if you are calling a control's method from a different thread, you must use one of the control's Invoke
methods to marshal the call to the proper thread. This property can be used to determine if you must call an Invoke method, which can be useful if you do not know what thread owns a control.
So one could use this to determine if an Invoke is actually required. CallingInvokeRequired/Invoke/BeginInvoke/EndInvoke
are all thread safe.
2、The worker thread raises the ReportWorkDone
event which is used by the UI, but when the UI attempts to use thisReportWorkDone EventArg
object properties to add items to the UI owned ListBox
control, you will get a crossthread violation, unless you do something to marshal the thread to the UI thread. This is know as thread affinity; thethread that creates the UI controls owns the controls, so any calls to the UI controls must go through the UI thread.
方法:
context = SynchronizationContext.Current;
context.Post(new SendOrPostCallback(delegate(object state) { this.lstItems.Items.Add(e.PrimeFound.ToString()); }), null);
41、通过远程桌面登录后,想查看远程电脑的任务管理器:
右键点击最下面一行,开始菜单栏那,选择“任务管理器”试试
42、获取网页编码
HttpWebRequest webRequest =(HttpWebRequest)WebRequest.Create(request.RawUrl);
WebRequest.DefaultWebProxy=null;//Ensure that we will not loop by going again in the proxy
HttpWebResponse response =(HttpWebResponse)webRequest.GetResponse();
string charSet = response.CharacterSet;
Encoding encoding;
if(String.IsNullOrEmpty(charSet))
encoding =Encoding.Default;
else
encoding =Encoding.GetEncoding(charSet);
StreamReader resStream =newStreamReader(response.GetResponseStream(), encoding);
return resStream.ReadToEnd();