簡體   English   中英

c#中的文本框值

[英]textbox value in c#

我剛剛將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();

如果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。

更新:如果您需要檢索學生的幾個屬性,那么我創建了類Student:

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;

如果您要搜索一組學生,請顯示名稱列表

當您獲得選擇時,獲取所選行的ID ...

你應該使用ComboBox / ListBox

  1. 將DataSource設置為DataTable
  2. 將ValueMember設置為“rowID”
  3. 設置DisplayMember =“StudentName”

現在你有一個像這樣的清單

-Tomer Weinberg
-aliprogrammer
-some freek

當您查詢myComboBox.SelectedValue時,您將獲得該學生的ID,如果未選擇任何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);
    }

祝你好運,

在我的舊帖子的評論之后,這是一個對話框示例

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表單。 獲取用戶選定的文件

祝你好運,享受。

您還可以使用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"]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM