首页 > 解决方案 > 如何从 MS Access 数据表中检索自动编号值并将其转换为 int64

问题描述

我想从列名“id”的 MS Access 数据表中检索一个自动数字值,并将其转换为 asp.net 中的 C# 中的 Int64。我该怎么做

标签: c#asp.netms-accessms-access-2007autonumber

解决方案


我们可能需要更多的上下文。

然而:

假设我们有这个标记:

      <asp:GridView ID="GridView1" runat="server" DataKeyNames="ID" CssClass="table" >
            <Columns>
                <asp:TemplateField HeaderText="Get ID" ItemStyle-HorizontalAlign="Center" >
                    <ItemTemplate>
                        <asp:Button ID="cmdGetID" runat="server" Text="Show ID" OnClick="cmdGetID_Click" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

然后这段代码填充网格。

   protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LoadGrid(); 
    }

    void LoadGrid()
    {
        using (OleDbCommand cmdSQL = 
            new OleDbCommand("SELECT ID, FirstName, LastName, HotelName, City FROM tblHotels ORDER BY HotelName",
            new OleDbConnection(Properties.Settings.Default.AccessDB)))
        {
            cmdSQL.Connection.Open();
            GridView1.DataSource = cmdSQL.ExecuteReader();
            GridView1.DataBind();
        }
    }

好的,我们现在有了这个:

在此处输入图像描述

好的,现在我们单击一行时的按钮代码 - 让我们从 Access 获取该 ID。

   protected void cmdGetID_Click(object sender, EventArgs e)
    {
        Button cmdSel = (Button)sender;
        GridViewRow gvRow = (GridViewRow)cmdSel.Parent.Parent;

        int MyID32 = Convert.ToInt32(gvRow.Cells[1].Text);
        Int64 MyID64 =  Convert.ToInt64(gvRow.Cells[1].Text);

        Debug.WriteLine("ID as Int 32 = " + MyID32);
        Debug.WriteLine("ID as Int 64 = " + MyID64);

        Int64 MyID64Fromtable = 0;

        DataTable rstData = new DataTable();
        using (OleDbCommand cmdSQL = new OleDbCommand("SELECT * FROM tblHotels where ID = @ID",
                                     new OleDbConnection(Properties.Settings.Default.AccessDB)))
        {
            cmdSQL.Connection.Open();
            cmdSQL.Parameters.Add("@ID", OleDbType.Integer).Value = MyID32;
            rstData.Load(cmdSQL.ExecuteReader());

            MyID64Fromtable = Convert.ToInt64(rstData.Rows[0]["ID"]);


        }
        // at this point, we have a 64 bit var called MyID64FromTable
        Debug.Print("64 ID value direct from table = " + MyID64Fromtable.ToString());
    }

输出:

ID as Int 32 = 307
ID as Int 64 = 307
64 ID value direct from table = 307

因此,该按钮代码从 Access(从网格)中提取 int32 值。

我们也为了好玩,创建了一个数据表。

用 Access 查询填充它,然后将 int32“ID”值(自动编号)从表中提取到变量中。

那么,真正从数据表中提取的一行?

这条线最像你要找的东西:

Int64 MyID64Fromtable = 0;
MyID64Fromtable = Convert.ToInt64(rstData.Rows[0]["ID"]);

推荐阅读