using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
int? a = null;
String connectionString = @"server=LT-1113\SQL2016;database=Employee;user=sa;password=envision1!";
Dictionary<int,String> d = new Dictionary<int,string>();
List<KeyValuePair<int?, String>> l = new List<KeyValuePair<int?, String>>();
using(SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand("select id,Name from details", con);
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
// Employee e = new Employee();
Console.WriteLine(reader.GetValue(0));
int id =(int)reader.GetInt32(0);//getting exception in this line
// if(reader.IsDBNull(id))
String Name = reader.GetValue(1).ToString();
l.Add(new KeyValuePair<int?,string>(id,Name) );
}
Console.WriteLine("Enter the Key");
bool b = false;
int mykey = Convert.ToInt32(Console.ReadLine());
String Value="";
foreach (KeyValuePair<int?, String> i in l)
{
if(i.Key == mykey)
{
Value=i.Value;
b = true;
}
// Console.WriteLine(i.Value);
}
if(b==true)
{
Console.WriteLine(Value);
}
else
{
Console.WriteLine("SORRY DATA NOT PRESENT");
}
//Console.ReadLine();
}
}
}
}
//this the code part
// **
strong text
****我的表具有列ID,并且将一行命名为varchar(20)name =“ ABC”和int id =“ NULL” **请先帮助我,谢谢****我的表具有列ID,并将名称行命名为varchar(20)name =“ ABC”和int id =“ NULL” **请先帮助我,谢谢****我的表具有列ID,并将一行命名为varchar(20)name =“ ABC”和int id =“ NULL” **请先帮助我,谢谢
通过指定IsDBNull
尝试columnname
int id = reader.IsDBNull("id") ? 0 : reader.GetInt32(reader.GetOrdinal("id"))