简体   繁体   中英

textbox value in c#

I just updated the StudentID and StudentName into the database.

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.

I mean i want to see value with StudentID, not ID row.

I don't want to use the ID row to see the StudentName.

I want to see StudentName when i enter StudentID.

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:

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

Otherwise use dt.Select method. Btw mixing data access code with UI code is not very good idea

UPDATE: also you can use 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:

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.

UPDATE: If you need to retrieve several attributes of student, then I'd created class 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:

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...

you should use ComboBox/ListBox

  1. set the DataSource to your DataTable
  2. set ValueMember to "rowID"
  3. set 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.

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()

you can add more information to get from the dialog...

really, it is kind of like using OpenFileDialog form. to get a User Selected File

Good Luck, Enjoy.

You can also use DataTable.Select method. You can pass filter expressions in it. It returns the DataRow Array

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

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

You can use the Select in this way :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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