比较或搜索后获取索引

时间:2016-07-20 07:03:24

标签: c# gridview indexing

我想问一下如何获取索引

public void cari()
        {
            SqlDataAdapter adapter = new SqlDataAdapter(command.CommandText, myConnection);
            try
            {
                ds.Tables.Clear();

                command.Connection = myConnection;
                command.CommandText = "select * from General.genre WHERE genre Like  '%"+textEdit1.Text.ToString()+"%' or code like '%"+textEdit1.Text+"%'";
                myConnection.Open();
                //  adapter.Fill(dt);

                var  buka = command.ExecuteReader();


                if (buka.Read())
                {

                    var x1 = buka[1].ToString();
                    textEdit2.Text = x1;
                    MessageBox.Show("asdas" + textEdit2.Text + ";");


                }
                else
                {
                    MessageBox.Show("type genre");
                }

上面的代码只显示字符串,但我想知道如何获取索引。也许代码在if (buka.read())之后?

enter image description here

2 个答案:

答案 0 :(得分:0)

以下代码行应该为您提供与列名对应的索引。

    @echo off
    title Led's Calculator
    color 1f
    mode con: cols=36 lines=12

    rem These are all set variables that can be used in this calc.
    set k=2.5
    :top
    echo -----------------------------------
    echo Welcome to Batch Calculator by Led
    echo -----------------------------------
    echo.
    set /p sum=
    set /a ans=%sum%
    echo.
    echo = %ans%
    echo -----------------------------------
    pause
    cls
    echo Previous Answer: %ans%
    goto top
    pause
    exit

如果您使用索引访问阅读器的字段,则无论如何都需要数字。

答案 1 :(得分:0)

我强烈建议您不要将UI输入中的字符串连接到SQL查询中。这很容易受到SQL注入的影响。而是使用SQL参数。

<强>解决方案:

将此SQL查询用作CommandText:

string query = "SELECT * FROM " +
                "(SELECT *, ROW_NUMBER()  OVER(ORDER BY(SELECT NULL)) [index] " +
                "FROM General.genre) R " +
                "WHERE [genre] LIKE '%" + textEdit1.Text.ToString() + "%' " +
                "OR [code] LIKE '%" + textEdit1.Text.ToString() + "%' ";
command.CommandText = query;

然后在你的阅读中使用:

var x1 = buka[1].ToString();
textEdit2.Text = x1;
var index = int.Parse(buka["index"]);
MessageBox.Show("asdas" + textEdit2.Text + "; Index = " + index );