可编辑的Gridview,代码来自ODBC的数据源

时间:2009-12-15 13:32:10

标签: asp.net gridview

我正在尝试创建一个小的gridview,其中列出了针对非标准SQL db的查询结果,并且使用此信息,我希望用户能够编辑一两列来更新db中的数据。我知道使用sqldatasource控件很容易,但我没有那么奢侈,当我触发gridview的编辑事件时,我无法从gridview中的itemTemplates切换到edittemplates。

任何指针?

一些代码:

<asp:GridView ID="ExamEditGridView" runat="server" OnRowEditing="EditExam" OnRowUpdating="SaveEdit"
        DataKeyNames="iproc_code" AllowSorting="true" AutoGenerateColumns="false" AutoGenerateEditButton="true">
        <HeaderStyle BackColor="#006633" Font-Bold="True" ForeColor="White" />
        <EditRowStyle BackColor="#999999" />
        <Columns>
            <asp:TemplateField HeaderText="Exam Title">
                <ItemTemplate>
                    <asp:Label ID="col1" runat="server" Text='<%# Bind("rpt_descrip") %>'></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="EditText" runat="server" Text='<%# Bind("rpt_descrip") %>' Visible="false" />
                </EditItemTemplate>
            </asp:TemplateField>
            <asp:BoundField HeaderText="Short Description" DataField="short_descrip" />
            <asp:BoundField HeaderText="Description" DataField="descrip" />
            <asp:BoundField HeaderText="Sched Note" DataField="sched_note" />
        </Columns>
    </asp:GridView>

代码背后: (查询只是一个simlpe select语句)

string mod_id = modSelect.SelectedValue;

        string query = qry + mod_id;

        using (OdbcConnection connection = new OdbcConnection(DbConnectionString))
        {
            OdbcDataAdapter adapter = new OdbcDataAdapter(query, connection);
            DataTable dt = new DataTable();
            connection.Open();
            adapter.Fill(dt);
            ExamEditGridView.DataSource = dt;
            ExamEditGridView.DataBind();
        }

当下拉列表列出索引更改时,gridview是数据绑定的,这为我提供了查询的mod_id

1 个答案:

答案 0 :(得分:2)

我最终得到它的工作,我没有意识到我必须设置gridview的editindex值和redatabind切换编辑模式

代码:

protected void EditExam(object sender, GridViewEditEventArgs e)
    {
        ExamEditGridView.EditIndex = e.NewEditIndex;
        ExamEditGridView.DataSource = Session["data"];
        ExamEditGridView.DataBind();
    }

protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
    {
        ExamEditGridView.EditIndex = -1;
        ExamEditGridView.DataSource = Session["data"];
        ExamEditGridView.DataBind();
    }