最近遇到的一些小问题汇总

 1、 类型“GridView”的控件“MainContent_GridView1”必须放在具有 runat=server 的窗体标记内

添加

public override void VerifyRenderingInServerForm(System.Web.UI.Control control)

        {

           

        }

 

 

2、每次点击修改按钮前,DropDownList的值丢失

protected void Page_Load(object sender, EventArgs e)

        {

            if (!IsPostBack)

            {

                ArrayList arrList = new ArrayList();

                arrList.Add("Red");

                arrList.Add("Green");

                arrList.Add("Blue");

                arrList.Add("LightGray");

                this.DropDownList1.DataSource = arrList;

                this.DropDownList1.DataBind();

                this.DropDownList1.Items.Insert(0, "请?选?择?列¢D表À¨ª项?");

            }

 

        }

 

        protected void Button1_Click(object sender, EventArgs e)

        {

            //若¨?没?加¨®!IsPostBack则¨°获?取¨?不?到Ì?DropdownList选?择?项?的Ì?值¦Ì

            this.Label1.Text = this.DropDownList1.Text;

        }

不判断IsPostBack将在点击Button时又重新引发事件Page_Load

这个算是ASP.NET的一个bug吧,如果你已经加了IsPostBack判断的话

这么解决吧,没发现其他好办法

用js
<SCRIPT language="javascript" type="text/javascript">
function aaa()
{
document.all("TextBox1").value = document.all('DropDownList1').options[document.all('DropDownList1').selectedIndex].text;
}

</SCRIPT>

在html代码中,给DropDownList1 加一个属性οnchange="aaa();"就行了
这里是把值放在TextBox1中

3、 TextBox修改后的值丢失

_DataMg.CurDataIndex = WebFormDepartmentInfo.index;

这句触发了回发,导致textBox回到初始状态,修改后的值丢失。

If(!IsPostBack)

{

   textBox1.Text=”初始值”;

}

 

 

 

 

 

4、                     路径问题

以default页引用calendar30.js为例

1、            在同级目录下:<script type="text/javascript" language="JavaScript" src="calendar30.js" charset="gb2312"></script>

2、            calendar30.js放在js文件夹里面

<script type="text/javascript" language="JavaScript"src="js/calendar30.js"charset="gb2312"></script>

 

3、            calendar30.js放在js文件夹里面,default放在Webs里面

  <script type="text/javascript" language="JavaScript"src="../js/calendar30.js"charset="gb2312"></script>

4、            default放在Webs里面

<script type="text/javascript" language="JavaScript" src="../calendar30.js" charset="gb2312"></script>

5、 VS2010有母版页的内容页里面添加对css和JavaScript的引用

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<script type="text/javascript" language="JavaScript" src="../Scripts/calendar30.js" charset="gb2312"></script>

    <div>

        <asp:TextBox ID="TextBox1" runat="server" OnClick="calendar()"></asp:TextBox>

    </div>

</asp:Content>

6、 Txt文本写入不全

读取多个文件时,读取完一个文件流没关闭,没写一个文件sw = File.CreateText(savePath + @"\" + dt.ToShortDateString() + ".txt");均会创建一个新的流,所以没读取完一个文件就应该立即关闭掉他,否则文件写入不全。

 

7、TextBox与RichTextBox显示"2011-10-12"(注意这个2011前面有个隐形的字符“.”)

private void button1_Click(object sender, EventArgs e)

        {

            string curText = "2011-10-12";

            rtbFile.Text += curText + "\n";

            this.textBox1.Text = curText;

        }

TextBox显示:2011-10-12

RichTextBox显示:

 

 

 

 

 

 

8、GetFrame  获取指定的堆栈帧

className = (new StackTrace(1, true)).GetFrame(0).GetMethod().ReflectedType.FullName.ToString();//第1层 frame.只能由要获取函数名的函数直接调用!

methodName = (new StackTrace(1,false)).GetFrame(0).GetMethod().Name.ToString();

 

public System.Reflection.PropertyInfo[] getPropertyInfo(object obj)
    {
        Type type = obj.GetType();
        Response.Write(type.ToString()+"<br/>");//得到类名
        System.Reflection.PropertyInfo[] ps = type.GetProperties();//得到所有属性(大写的访问器)
        return ps;
    }

 

 

C#反射机制,求出调用此方法的类名和方法名

 

public static void Write(string logLine, params object[] args)
        {
            System.Diagnostics.StackTrace ss = new System.Diagnostics.StackTrace();
            System.Reflection.MethodBase mb = ss.GetFrame(1).GetMethod();
            string functionName = mb.Name;
            string className = mb.DeclaringType.Name;
        }

 

 

// Get Type object of MyClass.

            Type myType=typeof(MyClass);      

            // Get the PropertyInfo by passing the property name and specifying the BindingFlags.

            PropertyInfo myPropInfo = myType.GetProperty("MyProperty", BindingFlags.Public | BindingFlags.Instance);

 

 

 

 

 

 

9、在屏幕上画图

using System.Runtime.InteropServices;

[DllImport("user32.dll ")]

        private static extern int GetDC(int hwnd);

 

System.IntPtr p = (IntPtr)GetDC(0);//   '取得屏幕

Graphics g = Graphics.FromHdc(p);

g.DrawRectangle(new Pen(Color.Black), new Rectangle(100, 100, 100, 100));

 

 

 

10、打印DataGridView

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;


/// <summary>
/// <para>打印DataGridView</para>
/// <para>用法:</para>
/// <para>   DataGridViewPrint dgvPrint = new DataGridViewPrint(new DataGridView[] { DataGridView1,DataGridView2 });</para>
/// <para>   dgvPrint.Print();</para>
/// </summary>
public class DataGridViewPrint
{
    private DataGridView[] dataGridView;
    private PrintDocument printDocument;
    private PageSetupDialog pageSetupDialog;
    private PrintPreviewDialog printPreviewDialog;

    private int dgvIndex = 0;

    private int rowCount = 0;
    private int colCount = 0;
    private int x = 0;
    private int y = 0;
    int i = 0;

    private int rowGap = 60;
    private int leftMargin = 50;
    private Font font = new Font("Arial", 10);
    private Font headingFont = new Font("Arial", 11, FontStyle.Underline);
    private Font captionFont = new Font("Arial", 10, FontStyle.Bold);
    private Brush brush = new SolidBrush(Color.Black);
    private string cellValue = string.Empty;



    public DataGridViewPrint(DataGridView[] dataGridView)
    {
        this.dataGridView = dataGridView;
        printDocument = new PrintDocument();
        printDocument.PrintPage += new PrintPageEventHandler(this.printDocument_PrintPage);
    }



    private void printDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
    {
        for (; dgvIndex < dataGridView.Length; dgvIndex++)
        {



            rowCount = dataGridView[dgvIndex].Rows.Count - 1;

            colCount = dataGridView[dgvIndex].ColumnCount;

            //print headings
            y += rowGap;
            x = leftMargin;
            for (int j = 0; j < colCount; j++)
            {
                if (dataGridView[dgvIndex].Columns[j].Width > 0)
                {
                    cellValue = dataGridView[dgvIndex].Columns[j].HeaderText;
                    e.Graphics.FillRectangle(new SolidBrush(Color.LightGray), x, y, dataGridView[dgvIndex].Columns[j].Width, rowGap);
                    e.Graphics.DrawRectangle(Pens.Black, x, y, dataGridView[dgvIndex].Columns[j].Width, rowGap);
                    e.Graphics.DrawString(cellValue, headingFont, brush, x, y);
                    x += dataGridView[dgvIndex].Columns[j].Width;
                }
            }
            //print all rows
            for (; i < rowCount; i++)
            {
                y += rowGap;
                x = leftMargin;
                for (int j = 0; j < colCount; j++)
                {
                    if (dataGridView[dgvIndex].Columns[j].Width > 0)
                    {
                        cellValue = dataGridView[dgvIndex].Rows[i].Cells[j].Value.ToString();
                        e.Graphics.DrawRectangle(Pens.Black, x, y, dataGridView[dgvIndex].Columns[j].Width, rowGap);
                        e.Graphics.DrawString(cellValue, font, brush, x, y);
                        x += dataGridView[dgvIndex].Columns[j].Width;
                    }
                }
                if (y >= e.PageBounds.Height - 80)
                {
                    // 允許多頁打印
                    y = 0;
                    e.HasMorePages = true;
                    i++;

                    return;
                }
            }
            y += rowGap;
            for (int j = 0; j < colCount; j++)
            {
                e.Graphics.DrawString(" ", font, brush, x, y);
            }
            i = 0;

        }
        e.HasMorePages = false;
    }


    public PrintDocument GetPrintDocument()
    {
        return printDocument;
    }

    public void Print()
    {
        try
        {
            pageSetupDialog = new PageSetupDialog();
            pageSetupDialog.Document = printDocument;
            pageSetupDialog.ShowDialog();
            printPreviewDialog = new PrintPreviewDialog();
            printPreviewDialog.Document = printDocument;
            printPreviewDialog.Height = 600;
            printPreviewDialog.Width = 800;
            printPreviewDialog.ShowDialog();
        }
        catch (Exception e)
        {
            throw new Exception("Printer error." + e.Message);
        }
    }
}

 

 

 

11、padding与margin

padding   是元素内补白,margin   是元素外边距

比如定义   span   {padding:   10px;   background-color:   red;}   那么   <span> abc </span>   看到的是一个红色块,而且不是紧贴   abc   的。

但是如果定义   span   {margin:   10px;   background-color:   red;}   ,那么   <span> abc </span>   的红色块边缘紧贴   abc   字符,但是周围有   10   个像素的边界

 

1.Margin

   用来设置页面中一个元素所占空间的边缘到相邻元素之间的距离.

   如果提供全部四个参数值,将按上-右-下-左的顺序作用于四边。
   如果只提供一个,将用于全部的四边。
   如果提供两个,第一个用于上-下,第二个用于左-右。
   如果提供三个,第一个用于上,第二个用于左-右,第三个用于下。

   在IE4+,margin属性不可用于td和tr对象。

   用法:body { margin: 36pt 24pt 36pt; }

2.Padding

   用来设置元素内容到元素边界的距离。

   如果提供全部四个参数值,将按上-右-下-左的顺序作用于四边。
   如果只提供一个,将用于全部的四条边。
   如果提供两个,第一个用于上-下,第二个用于左-右。
   如果提供三个,第一个用于上,第二个用于左-右,第三个用于下。
   内联对象要使用该属性,必须先设定对象的heightwidth属性,或者设定position属性为absolute。
   不允许负值。

   用法:body { padding: 36pt 24pt 36pt; }

 

12、DataGridView行头不显示

dataGridView1.RowHeadersVisible = false;

若是GridView

<asp:GridView ID="GridView1" runat="server" ShowHeader="false">
  </asp:GridView>

 

 

 

13、文件 "*.mdf" 已压缩,但未驻留在只读数据库或文件组中。必须将此文件解压缩。

1 右键点击数据库所在的文件夹,
2 点击属性,在常规选项卡中点击高级,
3 在弹出的窗口中的压缩或加密属性中去掉压缩内容或者节省磁盘空间,点击确定
4 点击应用,勾选应用于该文件夹所有文件 即可

 

 

 

 

 

 

 

 14、无法序列化   DataTable。未设置   DataTable   名称

 

在Web服务中用DataTable未设置名称就会报这个错误,解决方法:

DataTable dt=new DataTable();

dt.TableName = "MyTable";就OK了

当然也可不用Datatable而用DataSet

 

 

 15、不安全代码只会在使用/unsafe 编译的情况下出现

右击项目属性—》生成—》允许不安全代码

 

 

16、当控件被数据绑定时无法以编程方式向DataGridView的行集合中添加行

1、直接在dataset中增加的,dataset中增加,datagridview自然就增加了.

2、在数据绑定之前插入一个空行DataTable.Rows.insertat(DataTable.NewRow,位置),然后再绑定。
3、直接DataTable.Rows.Add(DataTable.NewRow)就是在最后一行加入一个空白行

4、添加一个 BindingSource所有的问题都解决了。首先是把数据源设给 BindingSource 的数据源。然后再把BindingSource设给 DataGridview 的数据源。需要使用BindingSource中转一下才可以。

5、调用datatable的insert方法插入到指定位置

 

 

 

 17、C#调用存储过程的返回值

 

因为一般都用T-SQL来执行数据库操作,偶尔现在转到用存储过程,竟然写不来调用过程的返回值了,查了很多资料,都不详细,或者没到点上,也许是我比较笨,呵呵。

C# 源代码

 1         /// <summary>
 2         /// 校验用户
 3         /// </summary>
 4         /// <param name="user">用户信息</param>
 5         /// <returns></returns>
 6         public static int VerifyUser(clsUser user)
 7         {
 8             int iRet;
 9             string sql = String.Format("EXECUTE VerifyUser @myVerifyReader OUTPUT,'{0}','{1}'",user.username,user.password); //执行的T-SQL串
10             SqlCommand scmd = new SqlCommand(sql, conn);
11             scmd.Parameters.Add(new SqlParameter("@myVerifyReader",SqlDbType.Int));
12             scmd.Parameters["@myVerifyReader"].Direction = ParameterDirection.Output;
13             //
14 
15             DBOpen(conn);
16             //执行scmd
17             scmd.ExecuteNonQuery();

 //获取返回值
18             iRet = (int)scmd.Parameters["@myVerifyReader"].Value;
19             DBClose(conn);
20             return iRet;
21         }


SQL SERVER存储过程

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


/*
* VerifyUser 存储过程
* 用途:验证用户登陆
*/
CREATE PROCEDURE VerifyUser
(
    @myVerifyReader int OUTPUT, --返回结果
    @username varchar(50), --用户名
    @userpassword varchar(50) --用户密码
)
AS
IF EXISTS(SELECT [id] FROM [Users] WHERE username = @username AND userpassword = @userpassword)
    SET @myVerifyReader = 0 --通过验证

ELSE IF EXISTS(SELECT [id] FROM [Users] WHERE username = @username)
    SET @myVerifyReader = 1 --用户存在,密码不正确
ELSE
    SET @myVerifyReader = 2 --用户不存在

RETURN  isnull(@myVerifyReader,3)
-------------------------------------------------
GO

 

 

 18、杀掉所有进程

using System.Diagnostics;

Process.GetCurrentProcess().Kill();

 

 

19、删除VSS项目

先删除解决方案目录、各个项目目录下的:
    mssccprj.scc 、
    工程名.vssscc、
    vssver.scc 、
    项目名.csproj.vspscc

这四类文件后,打开项目仍然报没删除干净,报下面错误:

再删除

SccProjectName = "SAK"  
        SccLocalPath = "SAK"
        SccAuxPath = "SAK"
        SccProvider = "SAK"

 

 

 

 20、无法将文件“obj\xx.*”复制到“bin\xx.*”。对路径“bin\xx.*”的访问被拒绝

将该文件的只读属性去掉即可

 

 

21、验证 (XHTML 1.0 Transitional): 元素“font”被视为已过时。建议使用较新的构造

font已经细分成了style=“font-family:,font-size:,color= “

例如:<style color="gray">请点击下边的文字……</style>

 

 22、当前上下文中不存在名称“Response

用System.Web.HttpContext.Current.Response.Write

 

23、alert弹不出来

用了ajax之后需要用System.Web.UI.ScriptManager.RegisterStartupScript(this,this.GetType(), null, "alert('已存在');", true);弹出

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值