code: I have read a example :The use girdview without datasource
file .cs
the example have run
now I want change the function GetDatasource following
but it not run :
It can binding but when I click update then it isn't update
who can help me
Code:
<asp:GridView AutoGenerateColumns="false" ID="GridView1"
runat="server" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:CommandField ShowEditButton="true" />
<asp:BoundField HeaderText="ID" DataField="ID"
ReadOnly="true" />
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%#
Eval("Name") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%#
Eval("Name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
GridView1.DataSource = GetDataSource();
GridView1.DataBind();
}
protected DataTable GetDataSource()
{
const string key = "MyDataSource";
DataTable dt = Session[key] as DataTable;
Session[key] = dt;
if (dt == null)
{
dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(1, "first object");
dt.Rows.Add(2, "second object");
dt.Rows.Add(3, "three object");
dt.Rows.Add(4, "four object");
Session[key] = dt;
}
return dt;
}
protected void GridView1_RowEditing(object sender,
GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void GridView1_RowCancelingEdit(object sender,
GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGrid();
}
protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
{
int id = int.Parse(GridView1.Rows[e.RowIndex].Cells[1].Text);
TextBox txtName =
GridView1.Rows[e.RowIndex].Cells[2].FindControl("txtName") as TextBox;
string newname = txtName.Text;
DataTable dt = GetDataSource();
DataRow[] rows = dt.Select("ID = " + id.ToString());
rows[0]["Name"] = newname;
GridView1.EditIndex = -1;
BindGrid();
}
}
now I want change the function GetDatasource following
Code:
protected DataTable GetDataSource()
{
SqlConnection conn = new SqlConnection("server =Nguyenlh;uid =sa;pwd =1221984;database =Test");
conn.Open();
string sql = "select * from table1 ";
SqlDataAdapter data = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
data.Fill(ds, "table1");
DataTable table = ds.Tables["table1"];
return table;
}
It can binding but when I click update then it isn't update
who can help me
Comment