我试图在gridview的编辑模式下更新数据。
它不能正确发送我的实际代码。我试图将其设置为HTML中的templateField,但它不起作用。这时,当我在gridview的编辑模式下修改日期时,程序中断。 放在Page_Load中。在对网格进行排序的条件下,网格已绑定。
if (ViewState["sorting"] == null)
{
String myquery = "Select * from Venituri";
SqlConnection sqlCon = new SqlConnection(CS);
SqlCommand cmd = new SqlCommand
{
CommandText = myquery,
Connection = sqlCon
};
SqlDataAdapter da = new SqlDataAdapter
{
SelectCommand = cmd
};
DataSet ds = new DataSet();
da.Fill(ds);
GridViewIncomes.DataSource = ds;
GridViewIncomes.DataSourceID = String.Empty;
GridViewIncomes.DataBind(); //here is a break when I was modified with the suggest code
}
protected void GridViewIncomes_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
SqlConnection sqlCon = new SqlConnection(CS);
int index = GridViewIncomes.EditIndex;
GridViewRow row = GridViewIncomes.Rows[index];
int VenitId = Convert.ToInt32(GridViewIncomes.DataKeys[e.RowIndex].Value);
string Denumire = ((TextBox)row.Cells[2].Controls[0]).Text.ToString().Trim();
var MyDateInsCalendar = GridViewIncomes.Rows[GridViewIncomes.EditIndex].FindControl("Data") as Calendar;
MyDateInsCalendar.Visible = false;
string Suma = ((TextBox)row.Cells[4].Controls[0]).Text.ToString().Trim();
string Descriere = ((TextBox)row.Cells[5].Controls[0]).Text.ToString().Trim();
string sql = "UPDATE Venituri SET Denumire='" + Denumire + "',Data='" + MyDateInsCalendar + "',Suma='" + Suma + "',Descriere='" + Descriere + "' WHERE VenitId=" + VenitId + "";
SqlCommand cmd = new SqlCommand(sql, sqlCon);
sqlCon.Open();
int temp = cmd.ExecuteNonQuery();
sqlCon.Close();
if (temp == 1)
{
lblSuccessMessage.Text = "Actualizat cu succes!";
}
GridViewIncomes.EditIndex = -1;
lblSuccessMessage.Text = "";
}
`
.aspx
<asp:BoundField HeaderText="Data" SortExpression="Data" DataField="Data" />
要将日期编辑到gridview中并在数据库中更新。
答案 0 :(得分:0)
您的MyDateInsCalendar
变量是一个对象(日历)。在您的SQL语句中使用此变量的属性之一。
例如:
<asp:GridView ID="GridView1" runat="server" AutoGenerateEditButton="true" OnRowEditing="GridView1_RowEditing" AutoGenerateColumns="false" OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Calendar ID="Calendar1" runat="server"></asp:Calendar>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}
private void BindGrid()
{
List<string> tmp = new List<string>();
tmp.Add("a");
GridView1.DataSource = tmp;
GridView1.DataBind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Calendar cal = GridView1.Rows[e.RowIndex].FindControl("Calendar1") as Calendar;
string tmp = cal.SelectedDate.ToString();
BindGrid();
}