在不使用数据库的情况下从datatable中搜索值(类似于like子句)

时间:2014-03-11 11:42:34

标签: c# asp.net webforms textbox

 public partial class WebForm4 : System.Web.UI.Page
   {
     protected void Page_Load(object sender, EventArgs e)
      {
        if (!(IsPostBack))
        {
            Session["List"] = null ;
        }
      }
     public static DataTable dt;
     public static int i = 1;
     // static int i = 1;
     //static List<string> lst; 
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        Session["List"] = dt;
        dt = new DataTable();
        DataRow dr = null;
      //  dt.Columns.Add(new DataColumn("RowNumber", typeof(int)));
        dt.Columns.Add(new DataColumn("Column1", typeof(string)));
      //  dt.Columns.Add(new DataColumn("Column2", typeof(string)));
      if (Session["List"] == null)
      {
          dr = dt.NewRow();
          dr["Column1"] = txtAdd.Text;
          dt.Rows.Add(dr);
      //    lst.Add(txtAdd.Text);

      }
      else if  (Session["List"] != null)
      {
          dt = (DataTable)Session["List"];
          dr = dt.NewRow();
          dr["Column1"] = txtAdd.Text;
          dt.Rows.Add(dr);
          //lst = (List<string>)Session["List"];
          //lst.Insert(i,txtAdd.Text);
          //i++;

      }
    }


    protected void btnNew_Click(object sender, EventArgs e)
    {
        List<string> lst = new List<string>();
        foreach (DataRow row in dt.Rows)
        {
            foreach (DataColumn col in dt.Columns)
            {
                lst.Add(row[col].ToString());

            }
        }
        for (int j = 0; j >= dt.Rows.Count; j++)
        {              
        }
        bool isfound = lst.Contains(txtSearch.Text);
        Response.Write(Convert.ToString(isfound));
        dlshow.DataSource = dt; // i want to bind only matching values to datalist 
        dlshow.DataBind();
    }
}

我有两个要添加的文本框,另一个是搜索我想只绑定那些匹配的文本框 值与搜索文本框匹配(如'Like'子句)我没有使用任何数据库

3 个答案:

答案 0 :(得分:0)

   //just this will do 

   protected void btnAdd_Click(object sender, EventArgs e)
    {
      List <string > lst = (List<string >)Session["List"];          
      lst.Add(txtAdd.Text);
      // Change the list in session with new list
      Session["List"] = lst;
    }

答案 1 :(得分:0)

这里的逻辑是错误的,就像你测试session [“list”]是否为null然后你想要做的操作但是如果session为null那么lst也将为null

 List <string > lst = (List<string >)Session["List"];
 lst.Add(txtAdd.Text);

答案 2 :(得分:0)

DataTable dt2 = dt.Select("Column1 Like '%" + txtSearch.Text + "%'").CopyToDataTable();
dlshow.DataSource = dt2; // i want to bind only matching values to datalist 
dlshow.DataBind();