简体   繁体   English

c#中的文本框值

[英]textbox value in c#

I just updated the StudentID and StudentName into the database. 我刚刚将StudentID和StudentName更新到数据库中。

I use these following codes to see value in the textbox but when i want to select the row it should be ID row not StudentID. 我使用以下代码来查看文本框中的值,但是当我想选择行时,它应该是ID行而不是StudentID。

I mean i want to see value with StudentID, not ID row. 我的意思是我希望看到StudentID的值,而不是ID行。

I don't want to use the ID row to see the StudentName. 我不想使用ID行来查看StudentName。

I want to see StudentName when i enter StudentID. 我想在输入StudentID时看到StudentName。

sql = new SqlConnection(@"Data Source=PC-PC\PC;Initial Catalog=Test;Integrated Security=True");
adapter = new SqlDataAdapter("select * from Entry",sql);
dt = new DataTable();
adapter.Fill(dt);
textBox1.Text = dt.Rows[3]["StudentName"].ToString();

If studentID is primary key of table, then use: 如果studentID是表的主键,则使用:

DataRow row = dt.Rows.Find(studentID);
if (row != null)
    textBox1.Text = row["StudentName"].ToString();

Otherwise use dt.Select method. 否则使用dt.Select方法。 Btw mixing data access code with UI code is not very good idea 顺便说一下,将数据访问代码与UI代码混合起来并不是一个好主意

UPDATE: also you can use LINQ 更新:你也可以使用LINQ

string name = (from row in dt.AsEnumerable()
              where row.Field<int>("StudentID") == studentID
              select row.Field<string>("StudenName"))
              .Single();

UPDATE: If you are entering student id and want to get student name, then you can just retrieve student name from database, passing parameter to sql command: 更新:如果您输入学生ID并想获得学生姓名,那么您可以从数据库中检索学生姓名,将参数传递给sql命令:

private string GetStudentName(int studentID)
{
    string connString = @"Data Source=PC-PC\PC;Initial Catalog=Test;Integrated Security=True";
    using (SqlConnection conn = new SqlConnection(connString))
    {
        string query = "SELECT StudentName FROM Entry WHERE StudentID = @studentID";
        SqlCommand cmd = new SqlCommand(query, conn);
        cmd.Parameters.Add("@studentID", SqlDbType.Int).Value = studentID;
        conn.Open();
        return (string)cmd.ExecuteScalar();
    }
}

Consider also returning only first entry (if StudentID is not PK) and verifying for DbNull. 考虑也只返回第一个条目(如果StudentID不是PK)并验证DbNull。

UPDATE: If you need to retrieve several attributes of student, then I'd created class Student: 更新:如果您需要检索学生的几个属性,那么我创建了类Student:

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Grade { get; set; }
}

And filled its properties from data reader: 并从数据阅读器填充其属性:

private Student GetStudent(int studentID)
{
    string connString = @"Data Source=PC-PC\PC;Initial Catalog=Test;Integrated Security=True";
    using (SqlConnection conn = new SqlConnection(connString))
    {
        string query = "SELECT * FROM Entry WHERE StudentID = @studentID";
        SqlCommand cmd = new SqlCommand(query, conn);
        cmd.Parameters.Add("@studentID", SqlDbType.Int).Value = studentID;
        conn.Open();
        SqlDataReader reader = cmd.ExecuteReader();

        if (!reader.Read())
             throw new Exception("Student not found");

        return new Student()
        {
            Id = (int)reader["StudentID"],
            Name = (string)reader["StudentName"],
            Grade = (string)reader["Grade"]
        };
    }
}

Then when you enter student id in text box, retrieve student from database and show its properties in controls: 然后,当您在文本框中输入学生ID时,从数据库中检索学生并在控件中显示其属性:

int studentID = Int32.Parse(idTextBox.Text);
Student student = GetStudent(studentID);
nameTextBox.Text = student.Name;
gradeTextBox.Text = student.Grade;

If you are searching to have a set of students, Show list of Names 如果您要搜索一组学生,请显示名称列表

and when you get the selection, get the ID of the selected Row... 当您获得选择时,获取所选行的ID ...

you should use ComboBox/ListBox 你应该使用ComboBox / ListBox

  1. set the DataSource to your DataTable 将DataSource设置为DataTable
  2. set ValueMember to "rowID" 将ValueMember设置为“rowID”
  3. set DisplayMember = "StudentName" 设置DisplayMember =“StudentName”

now you have a list like 现在你有一个像这样的清单

-Tomer Weinberg
-aliprogrammer
-some freek

and When you query myComboBox.SelectedValue you get the ID of that student or NULL if none is selected. 当您查询myComboBox.SelectedValue时,您将获得该学生的ID,如果未选择任何ID,则为NULL。

Edit 编辑

抓屏

put this inside a form with label and a listbox (can be combobox) 把它放在带有标签和列表框的表格内(可以是组合框)

    private DataTable dataTable1;
    public Form1()
    {
        InitializeComponent();

        dataTable1 = new DataTable("myTable");
        dataTable1.Columns.Add("id", typeof (int));
        dataTable1.Columns.Add("name", typeof(string));

        dataTable1.Rows.Add(1, "Tomer");
        dataTable1.Rows.Add(2, "Ali");
        dataTable1.Rows.Add(3, "Some Other");

        listBox1.SelectedValueChanged += new EventHandler(listBox1_SelectedValueChanged);

        listBox1.DataSource = dataTable1; // collection of Rows
        listBox1.ValueMember = "id"; // what is the value of the row.
        listBox1.DisplayMember = "name"; // what should be visible to user
        listBox1.Refresh();
    }

    void listBox1_SelectedValueChanged(object sender, EventArgs e)
    {
        label1.Text = string.Format("Selected: {0}", listBox1.SelectedValue);
    }

best of luck, 祝你好运,

Following the Comments on my old post, this is a Dialog box Example 在我的旧帖子的评论之后,这是一个对话框示例

public class MySearchForm
{
public string SelectedSID { get; private set;}
// code to show a list of Students and StudentsIDs.
}

public class myMainForm
{
    public void SearchButton_Click(object sender, EventArgs ea)
    {
        using(MySearchForm searchForm = new MySearchForm())
        {
            if(DialogResult.OK == searchForm.ShowDialog())
            {
                 mySutdentIDTextBox.Text = searchForm.SelectedSID;
            }
        }
    }
}

You can customize the Dialog box using the Constructor and setting parameters before calling ShowDialog() 您可以在调用ShowDialog()之前使用构造函数自定义对话框并设置参数

you can add more information to get from the dialog... 您可以添加更多信息以从对话框中获取...

really, it is kind of like using OpenFileDialog form. 实际上,它有点像使用OpenFileDialog表单。 to get a User Selected File 获取用户选定的文件

Good Luck, Enjoy. 祝你好运,享受。

You can also use DataTable.Select method. 您还可以使用DataTable.Select方法。 You can pass filter expressions in it. 您可以在其中传递过滤器表达式。 It returns the DataRow Array 它返回DataRow数组

DataRow [] rowCollection= dt.Select("StudentID=" + <From Some Control> or method argument)

Here is the link http://msdn.microsoft.com/en-us/library/det4aw50.aspx 这是链接 http://msdn.microsoft.com/en-us/library/det4aw50.aspx

You can use the Select in this way : 您可以这样使用Select:

DataTable dt = new DataTable("Test");
            dt.Columns.Add("ID") ;
            dt.Columns.Add("StudentID");
            dt.Columns.Add("StudentName");

            object[] rowVals = new object[3];
            rowVals[0] = "1";
            rowVals[1] = "ST-1";
            rowVals[2] = "Kunal Uppal";

            dt.Rows.Add(rowVals);
            string studentID = "ST-1"; //this can come from a textbox.Text property
            DataRow[] collection= dt.Select("StudentID=" + "'" + studentID + "'");
            string studentName = Convert.ToString(collection[0]["StudentName"]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM