I have a SQL Table where it contains one column all hexabinary values. While retrieving the data from the table in a grid view.I need to change all its value in a particular column with and then binding.
foreach (DataRow dr in ds.Tables[0].Rows)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
object o = dr["ColumnName"];
if (o != DBNull.Value) // Check for null
{
if (ds.Tables[0].Rows[i]["ColumnName"].ToString() != null)
{
ds.Tables[0].Rows[i]["ColumnName"] = value.ToString();
}
else
{ }
}
}
}
ds.Tables[0].AcceptChanges();
grid.DataSource = ds;
grid.DataBind();
I am trying to loop through only one particular column and change all the values in that. But it is failing. please help me
Since ds.Tables[0]
contains DataTable
object, you can use DataRow.Field<T>()
extension method to find values from specified column name, replace the values with SetField()
and then rebind changes to grid's data source:
foreach (DataRow dr in ds.Tables[0].Rows)
{
string oldValue = dr.Field<string>("ColumnName");
// check if the column has value
if (!string.IsNullOrEmpty(oldValue))
{
dr.SetField("ColumnName", value.ToString());
}
else
{
// do something else
}
}
ds.Tables[0].AcceptChanges();
// rebind the data source here
Note that DataRow.Field<T>
casts the value to type specified by T
type parameter, hence the following if-condition uses check against null
or empty string instead of DBNull.Value
.
first, bind
your grid view
and add OnRowDataBound
like
<asp:GridView ID="GridView1" runat="server" OnRowDataBound = "OnRowDataBound">
RowDataBound
event is triggered
for each GridView Row
when the GridView
Row is bound to data. then in your on OnRowDataBound
event code
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
column1 = e.Row.Cells[1].Text;
//here you can give the column no that you want get like e.Row.Cells[1]
e.Row.Cells[1].Text="test";
//you can set what you want like this
}
}
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.