2012-05-02 41 views
1

我刚更新了StudentID和StudentName到数据库中。c中的文本框值#

我使用下面的代码来查看文本框中的值,但是当我想选择行时,它应该是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(); 

回答

1

如果studentID是表中的主键,然后使用:

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

否则使用dt.Select方法。 与UI代码顺便说一句混合数据访问代码是不是很不错的主意

UPDATE:你也可以使用LINQ

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

UPDATE:如果要输入学生的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。

UPDATE:如果你需要找回学生的几个属性,那么我创建的类学生:

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; 
+0

它说表没有主键,但它有。 btw DataRow row = dt.Rows.Find(studentID);什么是studentid?这是studentid列吗? – aliprogrammer

+0

@aliprogrammer我不知道你在哪里得到studentID。这是你样本中的'3'。如果studentID不是PK,则使用Select方法'dt.Select(“StudentID =”+ studentID);'。顺便说一句,你如何获得学生证? –

+0

数字3是第三行,但不是学生ID。 – aliprogrammer

1

如果您正在寻找有一组学生,名称

,当你得到的选择,获得所选行的ID的显示列表...

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

  1. 设置DataSource到您的DataTable
  2. 集ValueMember为 “R​​OWID”
  3. 集DisplayMember = “StudentName”

现在你有一个像

-Tomer Weinberg 
-aliprogrammer 
-some freek 

列表,并在查询myComboBox.SelectedValue如果未选择任何你得到学生 或NULL的ID。

编辑

ScreenCapture

把这个带标签和一个列表框的表单内(可组合框)

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

好运,

+0

你能给我你正在谈论的代码吗?请使用代码示例编辑 – aliprogrammer

+0

@aliprogrammer。 –

+0

谢谢。我可以问你其他问题吗? – aliprogrammer

0

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

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

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

可以以这种方式使用的选择:

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"]); 
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之前设置的参数()对话框

你可以添加更多的信息,从对话框中得到...

真的,这是一种像使用打开文件对话框的形式。 得到一个用户选定的文件

好运,享受。

+0

顺便说一句你能回答我这个问题吗? http://stackoverflow.com/questions/10455663/connection-server-name – aliprogrammer