Freelancer
Freelancer

Reputation: 9074

extracting data from data set

Respected Users,

I am extracting data using data set. I want to put value in textbox. But value is not comming.

I have following Code

try
            {
                da = new SqlDataAdapter("select ID from Customer where Name='" + gvBkPendingSearch.SelectedRows[0].Cells[1].Value.ToString() + "'",con);
                DataSet ds = new DataSet();
                da.Fill(ds);
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    txtCustomerID.Text = ds.Tables[0].Rows[0].ToString();
            }
            catch (Exception ex)
            {

            }
            finally
            {
            }

txtCustomerID is my textbox. It is capturing value as>>>>>System.Data.DataRow

Error is in txtCustomerID.Text = ds.Tables[0].Rows[0].ToString();

but i am not able to understand it. Please help me.

Upvotes: 0

Views: 72370

Answers (2)

Pawan Nogariya
Pawan Nogariya

Reputation: 8970

change it like this

for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
   txtCustomerID.Text = ds.Tables[0].Rows[i]["ID"].ToString();

The mistake you are doing is, you are accessing this

ds.Tables[0].Rows[0].ToString();

means 0th row, the whole row!! not the column value

And the datatable row is System.Data.DataRow in .Net

Upvotes: 12

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

You need to select the column:

txtCustomerID.Text = ds.Tables[0].Rows[i][0].ToString();

Also note that you are overwriting the value of the textbox on each iteration of the loop. So what you will end up with is the ID of the last record in this textbox.

Also your query seems vulnerable to SQL injection. Personally I would recommend you scraping the DataSets in favor of an ORM or even plain old ADO.NET:

public static IEnumerable<int> GetIds(string name)
{
    using (var conn = new SqlConnection("Your connection string comes here"))
    using (var cmd = conn.CreateCommand())
    {
        conn.Open();
        cmd.CommandText = "select ID from Customer where Name=@Name";
        cmd.Parameters.AddWithValue("@Name", name);
        using (var reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                yield return reader.GetInt32(reader.GetOrdinal("ID"));
            }
        }
    }
}

And now you could happily use this function:

string name = gvBkPendingSearch.SelectedRows[0].Cells[1].Value.ToString();
int id = GetIds(name).FirstOrDefault();
txtCustomerID.Text = id.ToString();

Upvotes: 3

Related Questions