asp.net中DropDownList和GridView使用方法

作者:袖梨 2022-06-25

GridView常规用法

1、gridview前台界面代码

  gridview创建列最主要的有两种方式:

  1)数据绑定,表示数据绑定控件中作为文本显示的字段。DataField ="AnswerNum",AnswerNum是数据源中的一个字段。举例说明: 

 代码如下 复制代码


 

  2)使用模板创建,举例说明: 

 代码如下 复制代码



    
 
    

    

   ItemStyle是其模板样式,根据具体要求做出调整。

  
2、绑定数据源 

 代码如下 复制代码

this.gvQuestions.DataSource = ExamQuestionInfoList;
this.gvQuestions.DataBind();
this.gvQuestions.PageIndex = 0;
  gvQuestions为GridView控件,ExamQuestionInfoList为数据源,gridview的数据源可以是DataTable或者是数据集DataSet。

 

3、停留在某一行变色

 代码如下 复制代码


private void ChangeColor(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#E6F5FA'");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
    }
}

protected void gvQuestions_RowDataBound(object sender, GridViewRowEventArgs e)
{
ChangeColor(sender, e);
}


 
4、操作某一行
直接举例说明

 代码如下 复制代码


protected void gvSubjectiveOption_RowCommand(object sender, GridViewCommandEventArgs e)
{
    int rowSelected = Convert.ToInt32(e.CommandArgument);
    questionOptionInfo = QuestionOptionBLL.GetModel(rowSelected);

    //查看
    if (e.CommandName == "ViewSOption")
    {
this.tbOptionStem.Text = questionOptionInfo.QO_Option;
this.tbCorrectAnswer.Text = questionOptionInfo.QO_SubjectAnswer;//主观题答案
this.tbCorrectAnswerExplain.Text = questionOptionInfo.QO_Explain;

//选项附件
string optionAccessoryStr = questionOptionInfo.QO_Accessory;
string[] optionAccessoryArr = optionAccessoryStr.Split(',');
for (int i = 0; i < optionAccessoryArr.Length; i++)
{
    OptionAccessoryList.Add(optionAccessoryArr[i]);
}
BindOptionAccessoryList();
    }

    if (e.CommandName == "DeleteOption")
    {
QuestionOptionBLL.Delete(rowSelected);
int EQ_ID = questionOptionInfo.EQ_ID;
BindSubjectiveOption(EQ_ID);//重新绑定主观题问题信息
    }
}

e.CommandName对应前台界面的一些字段: 

 代码如下 复制代码




    




      
   

     
 

  

其中CommandName ="DeleteOption" CommandArgument ='<%# Bind("QO_ID") %>代表数据集中的某个字段。

  
5、添加Checkbox并且初始化台界面:

 代码如下 复制代码



    
 selectCorrectAnswer" CommandArgument ='<%# Bind("QO_ID") %>'>
          
 

后台逻辑: 

 代码如下 复制代码


///


/// 初始化checkbox
///

/// gridview控件
/// 数据源
/// checkbox控件名称
/// checkbox的值
private void InitializeCheckBox(GridView gv, DataTable dtSource, string cbName, string cbValue)
{
    int count = dtSource.Rows.Count;
    if (count > 0)
    {
for (int i = 0; i < count; i++)
{
    CheckBox cb = gv.Rows[i].FindControl(cbName) as CheckBox;

    if (cb != null)
    {
if (dtSource.Rows[i][cbValue].ToString() == "0")
{
    cb.Checked = false;
}
else
{
    cb.Checked = true;
}
    }
}
    }
}

DropDownList常规用法:

1、DropDownList绑定简单数据源

此处暂且写一个简单的数据源,只是为了说明效果。

 代码如下 复制代码

 

private void BindDropDownUp()
{
    ArrayList al = new ArrayList();
    al.Add("11");
    al.Add("22");
    al.Add("33");

    this.DropDownList1.DataSource = al;
    this.DropDownList1.DataBind();
}

 

  

获取DropDownList中选择的值:string text = this.DropDownList1.SelectedItem.Text;

2、DropDownList绑定较为复杂数据源

  此处从数据库中提取一个数据集ds,DropDownList控件的text框中显示一个值,选中后在后台可以获取绑定的value。具体如下:

 代码如下 复制代码


private void BindDropDownUp()
{
    string strSql = "select * from [OSCE].[dbo].[QuestionType]";
    DataSet ds = Query(strSql);

    this.DropDownList1.DataSource = ds;
    this.DropDownList1.DataTextField = "QT_Name";
    this.DropDownList1.DataValueField = "QT_ID";

    this.DropDownList1.DataBind();//将数据 www.111com.net 源绑定到类似( GridView) 控件
}

  

获取DropDownList控件text框的值:string text = this.DropDownList1.SelectedItem.Text;

  获取DropDownList控件绑定的value值:string text2 = this.DropDownList1.SelectedValue;

 

3、在页面初始化时直接给DropDownList赋值

  题外话:这个功能用的非常多,实现也很简单,但前提是你必须知道。找了好久才发现的。

 代码如下 复制代码
ListItem li = DropDownList1.Items.FindByText("外科");//外科是想显现的值,前提是DataTextField中必须有
    if (li != null)
    {
int index = DropDownList1.Items.IndexOf(li);
DropDownList1.SelectedIndex = index;
    }

 

一个简单的例子说明GridView与DropDownList结合的用法。

 代码如下 复制代码

                ForeColor="#333333" GridLines="None" AllowSorting="True" PageSize="6">
               
               
                   
                   
                   
                       
                                                            DataValueField="User_Sex" DataTextField="User_Sex">
                           

                       

                   

                   
               

               
               
               
               

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class GridView_DropDownList : System.Web.UI.Page
{
    SqlConnection sqlcon;
    string strCon = "Data Source=.SQL2005;DataBase=Users;Uid=sa;Pwd=123";

    protected void Page_Load(object sender, EventArgs e)
    {
        //DataTextFiled 获取或设置为列表项提供文本内容的数据源字段
        //DataValueField获取或设置为各列表项提供值的数据源字段
        if (!IsPostBack)
        {
            DropDownList ddl;
            string sqlstr = "SELECT * FROM Users";
            sqlcon = new SqlConnection(strCon);
            SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
            DataSet myds = new DataSet();
            sqlcon.Open();
            myda.Fill(myds, "AlLUser");
            GridView1.DataSource = myds;
            GridView1.DataBind();

            for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
            {
                DataRowView mydrv = myds.Tables["ALLUser"].DefaultView[i];
                if (Convert.ToString(mydrv["User_Sex"]).Trim() == "男")
                {
                    ddl = (DropDownList)GridView1.Rows[i].FindControl("DropDownList1");
                    ddl.SelectedIndex = 0;
                    ddl.SelectedItem.Text = "男";
                }
                else if (Convert.ToString(mydrv["User_Sex"]).Trim() == "女")
                {
                    ddl = (DropDownList)GridView1.Rows[i].FindControl("DropDownList1");
                    ddl.SelectedIndex = 1;
                    ddl.SelectedItem .Text = "女";
                }
            }
            sqlcon.Close();
        }
    }

    public SqlDataReader ddlBind()
    {
        string sqlstr = "SELECT DISTINCT User_Sex FROM Users";
        sqlcon = new SqlConnection(strCon);
        SqlCommand sqlcom = new SqlCommand(sqlstr, sqlcon);
        sqlcon.Open();
        return sqlcom.ExecuteReader();
    }
}

数据库:SQl2000 Northwind

效果如下

asp.net中DropDownList和GridView使用方法 

相关文章

精彩推荐