【问题标题】:textbox value in c#c#中的文本框值
【发布时间】:2012-05-12 00:41:50
【问题描述】:

我刚刚将 StudentID 和 StudentName 更新到数据库中。

我使用以下代码查看文本框中的值,但是当我想选择行时,它应该是 ID 行而不是 StudentID。

我的意思是我想查看 StudentID 的值,而不是 ID 行。

我不想使用 ID 行来查看 StudentName。

我想在输入 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();

【问题讨论】:

    标签: c# winforms dataset


    【解决方案1】:

    根据我旧帖子的评论,这是一个对话框示例

    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;
                }
            }
        }
    }
    

    您可以在调用 ShowDialog() 之前使用构造函数和设置参数自定义对话框

    您可以添加更多信息以从对话框中获取...

    真的,它有点像使用 OpenFileDialog 表单。 获取用户选择的文件

    祝你好运,享受。

    【讨论】:

    【解决方案2】:

    如果studentID是表的主键,那么使用:

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

    否则使用dt.Select 方法。 顺便说一句,将数据访问代码与 UI 代码混合并不是一个好主意

    更新:你也可以使用 LINQ

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

    更新:如果您正在输入学生 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();
        }
    }
    

    考虑只返回第一个条目(如果 StudentID 不是 PK)并验证 DbNull。

    更新:如果您需要检索学生的多个属性,那么我创建了学生类:

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

    并从数据读取器中填充其属性:

    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"]
            };
        }
    }
    

    然后,当您在文本框中输入学生 ID 时,从数据库中检索学生并在控件中显示其属性:

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

    【讨论】:

    • 它说该表没有主键,但它有。 btw DataRow row = dt.Rows.Find(studentID);什么是学生证?是 studentid 列吗?
    • @aliprogrammer 我不知道你从哪里得到学生 ID。这是您的示例中的3。如果 studentID 不是 PK,则使用 Select 方法dt.Select("StudentID = " + studentID);。顺便说一句,您如何获得学生证?
    • 数字 3 是第三行,但不是学生 ID。
    • @aliprogrammer 我从您的问题中了解到 - 您想通过 studentID 从学生的数据表名称中获取。那你想达到什么目的?
    • 我有三列(ID 是标识列并具有主键)(StudentID)(StudentName),当我输入学生 ID 时,它会显示学生名
    【解决方案3】:

    如果您正在寻找一组学生,请显示姓名列表

    当您获得选择时,获取所选行的 ID...

    你应该使用组合框/列表框

    1. 将 DataSource 设置为您的 DataTable
    2. 将 ValueMember 设置为“rowID”
    3. 设置 DisplayMember = "StudentName"

    现在你有一个类似的列表

    -Tomer Weinberg
    -aliprogrammer
    -some freek
    

    当您查询 myComboBox.SelectedValue 时,您将获得该学生的 ID 如果没有选择,则为 NULL。

    编辑

    把它放在带有标签和列表框的表单中(可以是组合框)

        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);
        }
    

    祝你好运,

    【讨论】:

    • 你能把你说的代码给我吗?请
    • 我有一个包含 StudentID 和 StudentName 的表。在我的表格中,我有一个 texbox。当我输入 StudentID 时,它将显示 StudentName。但想象一下,如果我们不知道自己的 StudentID。所以我做了一个搜索按钮。当我单击此按钮时,它将显示一个新表单,以便我可以通过键入 StudentName 来搜索 StudentID。现在的问题是,当我找到我的意图 StudentID 时,如何通过单击单元格来显示此 StudentID。我想当我单击单元格时,它会在第一个表单文本框中显示 StudentID。提前致谢
    • @aliprogrammer 哦,我回答了一个不同的问题...这称为对话框...我将在新答案中发布示例简单代码。
    【解决方案4】:

    您也可以使用 DataTable.Select 方法。您可以在其中传递过滤器表达式。它返回 DataRow 数组

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

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

    你可以这样使用 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"]);
    

    【讨论】:

      猜你喜欢
      • 2011-05-16
      • 1970-01-01
      • 2021-03-28
      • 2017-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多