I want to retrieve an auto number value from the MS Access data table from column name "id" and convert it to Int64 in C# in asp.net. How can I do it
Asked
Active
Viewed 72 times
-1
1 Answers
2
We probably need more context here.
However:
Say we have this markup:
<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>
And then this code to fill the grid.
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();
}
}
Ok, we now have this:
Ok, so now the button code when we click on a row - lets get that ID from Access.
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());
}
Output:
ID as Int 32 = 307
ID as Int 64 = 307
64 ID value direct from table = 307
So that button code pulls the int32 value from Access (from the grid).
We also for fun, created a data table.
Filled it with a Access query, and then pulled that int32 "ID" value (the autonumber) from the table into a variable.
So, the one line of really pulling from a data table?
this line is most like what you are looking for:
Int64 MyID64Fromtable = 0;
MyID64Fromtable = Convert.ToInt64(rstData.Rows[0]["ID"]);

Albert D. Kallal
- 42,205
- 3
- 34
- 51