转:ASP.NET程序中常用小技巧
登录:
private void btnLogin_Click(object sender, System.EventArgs e)
{
try
{
string sqlstr = "server = 192.168.0.57;uid = sa;pwd = sa;database = gaochao";
string sqlcom = "select * from chao where Name = '"+txtName.Text.Trim()+"' and Class = '"+txtPassWord.Text.Trim()+"'";
SqlConnection con = new SqlConnection (sqlstr);
SqlCommand com = new SqlCommand (sqlcom,con);
con.Open ();
SqlDataReader dr = com.ExecuteReader();
if(dr.Read())
{
Response.Write("<script>window.alert('登陆成功')</script>");
}
else
{
Response.Write("<script>window.alert('登陆失败')</script>");
}
con.Close();
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
}
数据帮定
private void dgBind()
{
string sqlcom = "select * from Student";
SqlConnection con = new SqlConnection (sqlstr);
SqlCommand com = new SqlCommand (sqlcom,con);
SqlDataAdapter da = new SqlDataAdapter (com);
DataSet ds = new DataSet ();
da.Fill(ds);
this.DataGrid1.DataSource = ds;
this.DataGrid1.DataBind();
}
/// <summary>
/// 取消事件
/// </summary>
/// <param name="source"></param>
/// <param name="e"></param>
private void DataGrid1_CancelCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
this.DataGrid1.EditItemIndex = -1;
dgBind();
}
/// <summary>
/// 编辑事件
/// </summary>
/// <param name="source"></param>
/// <param name="e"></param>
private void DataGrid1_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
this.DataGrid1 .EditItemIndex = e.Item .ItemIndex;
dgBind();
}
/// <summary>
/// 更改事件
/// </summary>
/// <param name="source"></param>
/// <param name="e"></param>
private void DataGrid1_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
string sqlcom = "update Student set Age = '"+((TextBox)e.Item .Cells[2].Controls[0]).Text+"',Sex = '"+((TextBox)e.Item .Cells[3].Controls[0]).Text+"', Class = '"+((TextBox)e.Item .Cells[4].Controls[0]).Text+"', Addr = '"+((TextBox)e.Item .Cells[5].Controls[0]).Text+"' where ID = '"+DataGrid1.DataKeys[e.Item .ItemIndex]+"'";
SqlConnection con = new SqlConnection (sqlstr);
SqlCommand com = new SqlCommand (sqlcom,con);
SqlDataAdapter da = new SqlDataAdapter (com);
DataSet ds = new DataSet ();
da.Fill(ds);
DataGrid1.EditItemIndex = -1;
dgBind();
Response.Write("<script>window.alert('更新成功')</script>");
}
/// <summary>
/// 删除事件
/// </summary>
/// <param name="source"></param>
/// <param name="e"></param>
private void DataGrid1_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
string sqlcom = "delete Student where ID = "+Convert.ToInt32(DataGrid1.DataKeys[e.Item .ItemIndex].ToString())+"";
SqlConnection con = new SqlConnection (sqlstr);
SqlCommand com = new SqlCommand (sqlcom,con);
SqlDataAdapter da = new SqlDataAdapter (com);
DataSet ds = new DataSet ();
da.Fill(ds);
dgBind();
}
一 ,打开新窗口并传递参数
(1)response.write("<script>window.open(’*.aspx?id="+this.DropDownList1.SelectIndex+"&id1="+...+"’)</script>")
接收参数:
string a = Request.QueryString("id");
string b = Request.QueryString("id1");
(2)Button跳转新页面
Response.Redirect("SaleOrderBackAdd.aspx?rsoId=" + rsoId.ToString()+"&Type=0");
Response.Write("<script>window.alert('合同" + mylabel.Text + " 未分配仓位');window.location='/XTMYWeb/Base/StoreRoom/StoreRoomShelfAllot.aspx';</script>"); //先提示后跳转页面
(3)Button打开新页面
<1>,private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
Button1.Attributes.Add("onclick","window.open('../Sale/ShowJobOrder.aspx?rsoId="+rsoId.ToString()+"&url=SaleOrderShow.aspx','新页面名称,'top=100%,left=80,toolbar=no, menubar=no,scrollbars=yes,"
+"resizable=yes, location=no, status=no, width=610,height=400');return false;");
}
}
<2>,
private void btnZSC_Click(object sender, System.EventArgs e)
{
int intID = common.GetOrderID(dgVIEWBuyOrderAll,"已审批",6);
QuMeiXJ.BLL.buyOrder bll = new QuMeiXJ.BLL.buyOrder();
if(intID == 0)
{
MessageBox.Show(this,"请选择一条已审批的数据!");
return;
}
if(intID == -1)
{
MessageBox.Show(this,"只能选择一条已审批的数据!");
return;
}
if(bll.GetisSea(intID)==1)
{
Response.Write("<script>window.open('../StoreRoom/OperZSCNum.aspx?Type=1','anyname','width=screen.width,height=screen.height');</script>");
dgBind();
}
else
{
MessageBox.Show(this,"只有国外订单可执行此操作!");
return;
}
}
(4)DataGrid打开新页面(也可以做打印)
(a)
把此列转换为模板列
(b)
<asp:TemplateColumn HeaderText="合同编号">
<HeaderStyle Width="9%"></HeaderStyle>
<ItemTemplate>
<a style="CURSOR: hand" onmouseover="this.style.color='#FF0000'" onmouseout="this.style.color='#000000'" onmousemove="this.style.color='#FF0000'"
href='SaleOrderShow.aspx?rsoId=<%# DataBinder.Eval(Container, "DataItem.rsoId") %>' target="_blank">
<%# DataBinder.Eval(Container, "DataItem.rsoCode") %>//该列的绑定字段
</a>
</ItemTemplate>
</asp:TemplateColumn>
(4)在后台做打印控制
(1),首先给datagrid/gridView添加一个"选择"列
(2)后台写事件代码:
datagrid:
private void dgdList_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
int OrderID = int.Parse(dgdList.Items[e.Item.ItemIndex].Cells[10].Text.Trim());
Response.Write("<script>window.open('../Print/batchSale/PrintbatchSalePick.aspx?BPickID="+OrderID+"','查看','top=100,left=100,toolbar=no,menubar=no,scrollbar=yes,resizable=yes,location=no,status=no,width=1000,height=800');</script>");
}
gridView:
protected void gvSaleOrder_SelectedIndexChanged(object sender, EventArgs e)
{
int id = Convert.ToInt32(gvSaleOrder.DataKeys[gvSaleOrder.SelectedIndex].Value.ToString());
Tools.Common.JavaScript.OpenWindow(this,"http://www.cnblogs.com/print/PrintSaleOrder2.aspx?id="+id);
}
(5)接收参数
{
get
{
try
{
return Convert.ToInt32(Request.QueryString["rsoId"]);
}
catch
{
return 0;
}
}
}
(6)
控制摸板列字段里TextBox的readonly属性
<1>点开摸板列里TextBox控件的属性,选择最上面的DataBindings属性
<2>在新窗口找到ReadOnly并在"自定义绑定表达式"里写上方法.例如:a==1?true:false
<3>在cs里写属性.例如:
public int a
{
set
{
b=0;
}
get
{
return b;
}
}
(6)DataGrad/GradView根据绑定列的值做不同的显示
例如:
(1),先把该列转换为摸板列
(2),编辑该列绑定方式
<asp:TemplateColumn HeaderText="有货架">
<HeaderStyle Width="7%" />
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Convert.ToInt32(DataBinder.Eval(Container, "DataItem.IsShelf")) == 0 ? "否":"是" %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
(7) 保存隐藏参数
<td>
<input id="OutStoreroomName" runat="server" name="OutStoreroomNameID" readonly=""
size="1" style="width: 24px; height: 20px" type="hidden" />
</td>
OutStoreroomName.Value="1"; //后台绑数据
二,Button的提示
(1)
Button1.Attributes.Add("onclick","return confirm(’确认?’)");
button.attributes.add("onclick","if(confirm(’are you sure...?’)){return true;}else{return false;}")
(2)
btnDel.Attributes.Add("onclick", "return confirm('确定删除该记录吗?');");
(3)DataGrid列删除提示
private void dgBank_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
(e.Item.Cells[4].Controls[0] as LinkButton).Attributes.Add("onclick","return confirm('确定要删除吗!');");
}
}
三,获取参数值
1,取DataGrid列值:
(1)取主键值
int ID = Convert.ToInt32(dgBank.DataKeys[e.Item .ItemIndex]);
(2)取列值
string Memo=(dgProduct.Items[i].Cells[7].Controls[1] as TextBox).Text;
int a = Convert.ToInt32((e.Item.Cells[2].Controls[0] as TextBox).Text);
string b = (e.Item.Cells[1].Controls[0] as TextBox).Text.Trim();
int c = Convert.ToInt32(e.Item.Cells[8].Text); //只读列
int d = Convert.ToInt32((e.Item.Cells[6].Controls[1] as DropDownList).SelectedValue.ToString()); //内嵌DropDownList控件
(3)循环DataGrid列表取值
(a)
private int rsoId()
{
int r = 0;
int rsoId = -1;
for(int i = 0; i < dgSaleOrder.Items.Count; i++)
{
if((dgSaleOrder.Items[i].Cells[0].FindControl("CheckBox") as CheckBox).Checked)
{
rsoId =Convert.ToInt32( dgSaleOrder.DataKeys[dgSaleOrder.Items[i].ItemIndex].ToString());
r++;
}
}
if(r == 0)
{
MessageBox.Show(this,"请选择一条数据");
return false;
}
if(r>1)
{
MessageBox.Show(this,"选择请不要多于一条数据");
return false;
}
else
{
return rsoId;
}
}
(b)
private string rsoId()
{
string rsoId = "";
for(int i = 0; i < dgSaleOrder.Items.Count; i++)
{
if((dgSaleOrder.Items[i].Cells[0].FindControl("CheckBox") as CheckBox).Checked)
{
rsoId+ =dgSaleOrder.DataKeys[dgSaleOrder.Items[i].ItemIndex]+",";
}
}
if(rsoId == "")
{
MessageBox.Show(this,"请选择一条数据");
return false;
}
else
{
rsoId= rsoId.Remove(rsoId.Length - 1,1);
return rsoId;
}
}
2,GridView 自段取值
(1)取主键值
int StoreMoveID = Convert.ToInt32(grvOperStoreMove.DataKeys[grvOperStoreMove.SelectedIndex].Value.ToString());
(2)取多个主键值
int RetailContractLadeID = Convert.ToInt32(GrvOperRetailContractLade.DataKeys[GrvOperRetailContractLade.SelectedIndex].Values["RetailContractLadeID"].ToString());
int RetailContractTypeID = Convert.ToInt32(GrvOperRetailContractLade.DataKeys[GrvOperRetailContractLade.SelectedIndex].Values["RetailContractTypeID"].ToString());
(3)循环取主键值
gvBaseBank.DataKeys[gvBaseBank.Rows[i].DataItemIndex].Value.ToString()
(4)取列值
string RetailContractCode = grwOperRetailBContract.Rows[grwOperRetailBContract.SelectedIndex].Cells[1].Text; //选中取值
model.productID = Convert.ToInt32(grvOperStoreMoveDetail.Rows[i].Cells[0].Text);
四,表格点击改变颜色
if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem)
{
e.Item.Attributes.Add("onclick","this.style.backgroundColor=’#99cc00’;
this.style.color=’buttontext’;this.style.cursor=’default’;");
}
写在DataGrid的_ItemDataBound里
if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem)
{
e.Item.Attributes.Add("onmouseover","this.style.backgroundColor=’#99cc00’;
this.style.color=’buttontext’;this.style.cursor=’default’;");
e.Item.Attributes.Add("onmouseout","this.style.backgroundColor=’’;this.style.color=’’;");
}
五,Datagrid增加自动编号列
(正序)
1<asp:DataGrid id="DataGrid1" runat="server">
2 <Columns>
3 <asp:TemplateColumn>
4 <ItemTemplate>
5 <%# Container.ItemIndex + 1%>
6 </ItemTemplate>
7 </asp:TemplateColumn>
8 </Columns>
9 </asp:DataGrid>
(倒序)
<asp:DataGrid id="DataGrid1" runat="server" AllowPaging="True">
2 <Columns>
3 <asp:TemplateColumn>
4 <ItemTemplate>
5 <%# RowsCount - DataGrid1.CurrentPageIndex * DataGrid1.PageSize - Container.ItemIndex %>
6 </ItemTemplate>
7 </asp:TemplateColumn>
8 </Columns>
9 </asp:DataGrid>
五,GridView自动序号
(倒序)
<asp:TemplateField HeaderStyle-Width="30px" HeaderText="序号" ItemStyle-HorizontalAlign="center">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%#((Container as GridViewRow).DataItem as System.Data.DataRowView).Row.Table.Rows.Count - (Container as GridViewRow).RowIndex%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
(正序)
<asp:TemplateField HeaderStyle-Width="30px" HeaderText="序号" ItemStyle-HorizontalAlign="center">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%#(Container as GridViewRow).RowIndex + 1%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
六,一个按钮实现添加和更改两个功能
private void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["U_ID"] == null || Request.QueryString["U_ID"].ToString() == string.Empty || Convert.ToInt32(Request.QueryString["U_ID"]) < 1)
{
btnSave.CommandName ="insert";
btnSave.Text="添加";
}
else
{
btnSave.CommandName="update";
btnSave.Text="更改";
}
}
}
private void btnSave_Click(object sender, System.EventArgs e)
{
if(Page.IsValid)
{
if(btnSave.CommandName == "insert")
{
Add();
}
else
{
Edit();
}
}
}
七,关于日期格式
1,页面按钮显示:
lblsendtime.Text = Convert.ToDateTime(m_table.Rows[0]["sendtime"]).ToString("yyyy-MM-dd"); //2007-04-05
lblsendtime.Text = Convert.ToDateTime(m_table.Rows[0]["sendtime"]).ToString("yyyy年MM月dd日 ddd");
//2007年04月05日 星期五
2,DataGrid列显示时间:
{0:yyyy-mm-dd}
八,CheckBox (全选或全不选)
private void btnSelectAll_Click(object sender, System.EventArgs e)
{
for(int i = 0; i < dgMessage.Items.Count; i++)
{
if(((CheckBox)dgMessage.Items[i].Cells[0].FindControl("CheckBox1")).Checked)
{
((CheckBox)dgMessage.Items[i].Cells[0].FindControl("CheckBox1")).Checked = false;
}
else
{
for(int r = 0; r < dgMessage.Items.Count; r++)
{
((CheckBox)dgMessage.Items[r].Cells[0].FindControl("CheckBox1")).Checked = true;
}
return;
}
}
}
九,对一组以逗号分隔的字符串ID值循环
string strID;
string[] strID = importIDs.Split(',');
for(int i = 0;i < strID.Length; i++)
{
Update saleOrder set name=** where rsoId=strID[i]
}
十,绑定DropDownList控件
private void drpOrderStatusBind()
{
QuMeiXJ.BLL.batchSaleStatus bll = new QuMeiXJ.BLL.batchSaleStatus();
DataSet ds = bll.GetList("1=1");
drpOrderStatus.DataTextField = "bathSaleSName";
drpOrderStatus.DataValueField = "bathSaleSID";
drpOrderStatus.DataSource = ds;
drpOrderStatus.DataBind();
drpOrderStatus.Items.Insert(0,new ListItem("全部","-1"));
}
十,在DataGrid里绑定DropDownList控件
(1),将要绑定的列转换为摸板列,在EditItemTemplate里放入DropDownList,在ItemTemplate里放Label
(2),在CS里写绑定数据属性:
public DataTable drpDepNameU
{
get
{
XTMYSale.BLL.ConfDep bll = new XTMYSale.BLL.ConfDep();
return bll.GetList("1=1").Tables[0];
}
}
(3),设置页面:
<asp:TemplateColumn HeaderText="所属部门">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataSource="<%#drpDepNameU%>"
DataTextField="DepName" DataValueField="DepID">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateColumn>
十,事务
SqlConnection m_cn = new SqlConnection();
m_cn.ConnectionString = SqlHelper.connectionString;
m_cn.Open();
SqlTransaction myTran = m_cn.BeginTransaction();
try
{
SqlParameter[] parameters = {
new SqlParameter("@buyOrderID", SqlDbType.VarChar,200)};
parameters[0].Value = buyOrderID;
SqlHelper.ExecuteNonQuer(myTran,CommandType.StoredProcedure,"UP_buyOrder_Delete",parameters);
myTran.Commit();
return true;
}
catch
{
myTran.Rollback();
return false;
}
finally
{
myTran.Dispose();
m_cn.Close();
m_cn.Dispose();
}
十一,根据条件转换字符
例:把逗号转化为换行
m_table.Rows[i]["备注"] = m_table.Rows[i]["备注"].ToString().Replace(",","<br>").Replace(",","<br>");
十二,ArrayList的使用
private System.Collections.ArrayList getList()
{
int oldNum;
int newNum;
System.Collections.ArrayList m_lst = new ArrayList();
for (int j = 0; j < grvOperStoreMoveDetail.Rows.Count; j++)
{
oldNum = int.Parse(grvOperStoreMoveDetail.Rows[j].Cells[4].Text);
try
{
newNum = int.Parse((grvOperStoreMoveDetail.Rows[j].Cells[6].Controls[1] as TextBox).Text);
}
catch
{
Tools.Common.JavaScript.MessageBox(this, "输入数据不正确!");
return null;
}
if (newNum > oldNum)
{
Tools.Common.JavaScript.MessageBox(this, "产品:" + grvOperStoreMoveDetail.Rows[j].Cells[1].Text + "入库数不能大于产品数!");
return null;
}
else if (newNum != 0)
{
XTMYSale.Model.OperStoreInDetail model = new XTMYSale.Model.OperStoreInDetail();
model.OrderDetailID = Convert.ToInt32(grvOperStoreMoveDetail.Rows[j].Cells[7].Text);
model.productID = Convert.ToInt32(grvOperStoreMoveDetail.Rows[j].Cells[0].Text);
model.productNum = Convert.ToInt32((grvOperStoreMoveDetail.Rows[j].Cells[6].Controls[1] as TextBox).Text);
model.productWholesalePrice = Convert.ToDecimal(grvOperStoreMoveDetail.Rows[j].Cells[5].Text);
model.productMaterial = grvOperStoreMoveDetail.Rows[j].Cells[3].Text.Replace(" ", "");
model.StoreroomShelfID = 0;
if (model != null)
{
m_lst.Add(model);
}
else
{
return null;
}
}
}
return m_lst;
}