Quantcast
Channel: ADO.NET, Entity Framework, LINQ to SQL, NHibernate
Viewing all 1698 articles
Browse latest View live

query based on languange one to many relation entity framewok

$
0
0

I want to query translation based on langunage name, Below is my ef scheme

 public class Noun
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<TranslationNoun> Translations { get; set; }
}
public class TranslationNoun
{
    public int Id { get; set; }
    public string Content { get; set; }
    [ForeignKey("LangungeId")]
    public Langunge Langunge { get; set; }
    public int NounId { get; set; }
    [ForeignKey("NounId")]
    public Noun Noun { get; set; }
}
public class Langunge
{
    public int Id { get; set; }
    public string Name { get; set; }
}

So here is sample data

Language: Id=1,Name = English

Language: Id=2,Name = Franche

Language: Id=3,Name = Indonesia

Noun: id=1,Name="Makan";

TranslationNoun : id=1, Content=Eat, LanguageId=1,NounId=1

TranslationNoun : id=2, Content=Le menger, LanguageId=2,NounId=1

TranslationNoun : id=3, Content=Mangan, LanguageId=3,NounId=1

I want to focus on Noun table, how do i query and show Noun Translation Based on Languange Name:

Example When user choose English Language then it will return

Noun 1,Makan,Eat

When user choose Indonesia Language then it will return

Noun 1,Makan,Mangan

When user choose Francje Language then it will return

Noun 1,Makan,Le menger

Thanks for your nice attention.


Linq to XML query set Namespace

$
0
0

I know is there a way, in Expression bellow to mention NameSpace, but I'm not finding any doc about this particular notation. There was many docs some years ago

Dim XDoc as XDocument = XDocument.Parse(MyStringXML)
Dim MyNode = (From p in XDoc.<main>.<state>.<city> select p.<name>). FirstOrDefault

How can I set Namespace?
I do not want use Element, ChildElement as actual docs suggests

When I try use .include() to include just 1 field from foreign table EF gets mad

$
0
0

Hi all,

I got  EF dbset find results as JSON via jquery.getJSON function.

and I want to add just 1 field from foreign table like this

_context.Set<MyDbSet>().Where(e => e.id== theIdIWant).Include(e=>e.myforeigntable.TheFieldIWant); 

however it gets mad and says "reset connection with server" in chrome console when I started JS function.

But if I use like this  (all data not just one field) _context.Set<MyDbSet>().Where(e => e.id== theIdIWant).Include(e=>e.myforeigntable);

It works.

I know it will overload (may be little but still important) the server callin all the fields in foreign table and also getting it as JSON. 

Is there any way to solve it?

I tried this but didn't help

 services.AddMvc().AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                options.SerializerSettings.DateFormatString = "dd/MM/yyyy";
//this line supposed to stop this errror options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; });

What is the best practice to save an html table to EF table via jquery.post()

$
0
0

Hi all,

Lets say you have relatively big html table 30 fields 10-2000 raw

And you let your users to change its values (via contenteditable like approach) and then you uploat it to an EF dataset via jquery.post.

The thing is if you simply convert your table into jason and send it, you will send tons of unnecessary updates and make the network and server overloaded.

However if you put forexample simple codes to onexit function of the table elements and save the changed data immediatly. It looks perfect but I can't be sure if everytime I catch the action (data safety concerns)

What do you say about it?

Thank you

What if I don't use "using" for my context

$
0
0

Hi all,

I simply get my data from context with the technique below

private readonly EvrakaContext _context;

public NumuneKabulController(EvrakaContext context)
{
_context = context;
}


public JsonResult NumuneSahibiBul(string ArananNumuneSahibi)
{
IQueryable<NumuneSahipleri> bulunanNumuneSahipleri = _context.NumuneSahipleri.Where(e => e.Adisoyadi.Contains(ArananNumuneSahibi)).Include(e => e.Evraklar).OrderByDescending(e => e.EvraklarId);
return Json(bulunanNumuneSahipleri);
}

however, as you see my context is not IDisposable and this make me concern about my server's RAM.

What do you think?

LINQ lambda syntax for counting number of sequence

$
0
0

Hello all,

I got table Student records in database as follows:

ExamDate         Test           Result
01/21/2016         Math           Pass
06/02/2016         Art               Pass
05/31/2017         Math           Fail
06/28/2017         Art              Pass
07/03/2017         Math          Pass
07/19/2017         Art              Fail
08/01/2017         Math          Fail
09/13/2017         Art              Fail
09/15/2017         Math          Fail
10/01/2017         Art              Fail
10/10/2017         Math          Pass
10/11/2017         Art             Fail

....

In above sample data, there are 3 consecutive fails (yellow highlight) for Art test and 1 consecutive fail (blue highlight) for Math test. Anyone can help me to write LINQ lambda to counting how many sequential consecutive fails each test (Math, Art) based on sorting exam date?

Thanks in advance.

TimeDate ID Field

$
0
0

Can a TimeDate field be used as an ID?

Do you treat it like any ID property: name the property the standard ID name ("PropertySetNameID")?

Primary v Foreign Key

$
0
0

Can a foreign key be designated that is not a primary ID?


Can I use a string variable to define dataset field like mydataset.[myvar]=

$
0
0

Hi all,

I want to update a table field using the pseudo action like below 

is it possible to do this?

public void save(int id, string field, string value)
{
try
{
MyDBSet mydbset= _context.mydbset.First(a => a.id== id);
mydbset.[field] = value;

}

Creation of tables with filegroups in Entity framework

$
0
0

Hi

I would like to create tables with filegroups in EF:

For instance I have a table:

 public class Almacen
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Almacen()
        {
            SolicitudAlmacenOrigen = new HashSet<Solicitud>();
            SolicitudAlmacenDestino = new HashSet<Solicitud>();
            UbicacionAlmacen = new HashSet<UbicacionAlmacen>();
            AgrupacionAlmacen = new HashSet<AgrupacionAlmacen>();
            Requerimiento = new HashSet<Requerimiento>();
            RequerimientoAlmacen = new HashSet<RequerimientoAlmacen>();
        }

        public Guid Id { get; set; }

        [Required]
        [StringLength(8)]
        public string Codigo { get; set; }

        [Required]
        [StringLength(4)]
        public string CodigoAlmacen { get; set; }

And I have its relations:

public class AlmacenConfiguration : EntityTypeConfiguration<Almacen>
    {
        public AlmacenConfiguration()
        {
            this.ToTable("Inv.Almacen")
                .HasKey(e => e.Id);

            this
                .Property(e => e.Codigo)
                .IsFixedLength()
                .IsUnicode(false);

            this
                .Property(e => e.CodigoAlmacen)
                .IsFixedLength()
                .IsUnicode(false);

            this
                .Property(e => e.CodigoCentro)
                .IsFixedLength()
                .IsUnicode(false);

            this
                .Property(e => e.Nombre)
                .IsUnicode(false);

            this
                .Property(e => e.IdSociedad)
                .IsFixedLength()
                .IsUnicode(false);

            this
                .Property(e => e.IdSistemaOrigen)
                .IsFixedLength()
                .IsUnicode(false);

            this
                .HasMany(e => e.SolicitudAlmacenDestino)
                .WithRequired(e => e.AlmacenDestino)
                .HasForeignKey(e => e.IdAlmacenDestino)
                .WillCascadeOnDelete(false);

            this
                .HasMany(e => e.SolicitudAlmacenOrigen)
                .WithOptional(e => e.AlmacenOrigen)
                .HasForeignKey(e => e.IdAlmacenOrigen);

            this
                .HasMany(e => e.UbicacionAlmacen)
                .WithRequired(e => e.Almacen)
                .HasForeignKey(e => e.IdAlmacen)
                .WillCascadeOnDelete(false);

            this
                .HasMany(e => e.AgrupacionAlmacen)
                .WithOptional(e => e.Almacen)
                .HasForeignKey(e => e.IdAlmacen)
                .WillCascadeOnDelete(false);

            this
                .HasMany(e => e.Requerimiento)
                .WithRequired(e => e.AlmacenDestino)
                .HasForeignKey(e => e.IdAlmacenDestino)
                .WillCascadeOnDelete(false);

            this
                .HasMany(e => e.RequerimientoAlmacen)
                .WithRequired(e => e.AlmacenOrigen)
                .HasForeignKey(e => e.IdAlmacenOrigen)
                .WillCascadeOnDelete(false);

            this
                .HasMany(e => e.AlmacenCoordenada)
                .WithRequired(e => e.Almacen)
                .HasForeignKey(e => e.IdAlmacen)
                .WillCascadeOnDelete(false);
        }
    }

MVC with EntityFramework, in an AngularJS project

$
0
0

Hello everybody,

With Visual Studo 2017, in an Angular type web project, I installed EntityFrameworkCore (it took time as I had to install each dependency individually).

As I try to create a controller, I am proposed Entity Framework only for a WebAPI controller, not for a MVC one. I can create a "MVC controller with read/write actions", but without EntityFramework, so if I create that I am not asked for a class on which to create a table.

I feel I already did that ?

Oh, perhaps it is not compatible with .Net Core ?

What is nice with MVC is its ability to create a collection of web pages in two shakes, so that I can seize data in them, and then begin the real work, with the necessary set to test it.

In a project with just MVC it is quite OK, even with WebAPI in it, but I should like it to work with AngularJS too.

Entityframework Turkish charset "contains" problem

$
0
0

Hi all,

in Turkish we use İ as big i and we also have another letter which is " ı " (which is not i ) and this cause problem for EF to find the record with contains.

for example, it couldn't find "Bozyazı"

ps the database is MySQL

LINQ: How to handle situation when joining two object & when one is null

$
0
0

see my below code. here i am joining two list<t> object QCViewAllBrokerList and customformulaList  but some time one could be null. my below query throwing error when 

customformulaList is null. i want to write a query which will work smoothly when one object is null. please guide me how to restructure my below code when one linq object is null. thanks

varQCViewAllHistValue=(from viewalllst inQCViewAllBrokerList
			  join frmlst in customformulaList
			  on new{
			      val =String.IsNullOrEmpty(viewalllst.ViewAllSection)?"": viewalllst.ViewAllSection.Trim().ToUpper(),
			      val1 =String.IsNullOrEmpty(viewalllst.ViewAllLineItem)?"": viewalllst.ViewAllLineItem.Trim().ToUpper(),
			      val2 =String.IsNullOrEmpty(viewalllst.ViewAllPeriod)?"": viewalllst.ViewAllPeriod.Replace("A","").Replace("E","").Trim().ToUpper(),
			      val3 =String.IsNullOrEmpty(viewalllst.ViewAllBroker)?"": viewalllst.ViewAllBroker.Trim().ToUpper()}

			  equals new{
			      val =String.IsNullOrEmpty(frmlst.Section)?"": frmlst.Section.Trim().ToUpper(),
			      val1 =String.IsNullOrEmpty(frmlst.Li)?"": frmlst.Li.Trim().ToUpper(),
			      val2 =String.IsNullOrEmpty(frmlst.Period)?"": frmlst.Period.Replace("A","").Replace("E","").Trim().ToUpper(),
			      val3 =String.IsNullOrEmpty(frmlst.Broker)?"": frmlst.Broker.Trim().ToUpper()}into tempJoinfrom leftJoin in tempJoin.DefaultIfEmpty()where viewalllst.Wtg=="1"selectnewQCHelper(){Broker= viewalllst.ViewAllBroker==null?string.Empty: viewalllst.ViewAllBroker,Section= viewalllst.ViewAllSection==null?string.Empty: viewalllst.ViewAllSection,Li= viewalllst.ViewAllLineItem==null?string.Empty: viewalllst.ViewAllLineItem,Period= viewalllst.ViewAllPeriod==null?string.Empty: viewalllst.ViewAllPeriod,CrossCalc1Q= leftJoin ==null?string.Empty: leftJoin.CrossCalc1Q,CrossCalc2Q= leftJoin ==null?string.Empty: leftJoin.CrossCalc2Q,CrossCalc3Q= leftJoin ==null?string.Empty: leftJoin.CrossCalc3Q,CrossCalc4Q= leftJoin ==null?string.Empty: leftJoin.CrossCalc4Q,CrossCalcFY= leftJoin ==null?string.Empty: leftJoin.CrossCalcFY,Value= viewalllst.Value==null?string.Empty: viewalllst.Value,QCFormula= leftJoin ==null?string.Empty: leftJoin.QCFormula,CustomFormula= leftJoin ==null?string.Empty: leftJoin.CustomFormula,Historical= leftJoin ==null?string.Empty:String.IsNullOrEmpty(leftJoin.Historical)?"": leftJoin.Historical,DeriveCrossCalc= leftJoin ==null?string.Empty: leftJoin.DeriveCrossCalc}).ToList<QCHelper>();

Can we use LINQ to populate my object instead of foreach loop

$
0
0

I am using nested foreach loop to populate my object WeightageRowNumberall. foreach taking long time when there is huge data and many iteration.

this is my foreach code

foreach(var data inOrderWiseLineItem){// string Li = data1.LineItem;string section = data.Section;stringLi= data.Lineitem;if(!String.IsNullOrEmpty(Li)&&!String.IsNullOrEmpty(section)){// for broker rowforeach(var broker inDistinctBroker){
                                    rowNumber = rowNumber +1;
                                    brokerRowWeightageRowNumber =newWeightageRowNumber();
                                    brokerRowWeightageRowNumber.Section= section;
                                    brokerRowWeightageRowNumber.Lineitem=Li;
                                    brokerRowWeightageRowNumber.Broker= broker;
                                    brokerRowWeightageRowNumber.RowNumber= rowNumber;
                                    brokerRowWeightageRowNumber.Weightage=(int)RowWeightage.BrokerRow;WeightageRowNumberall.Add(brokerRowWeightageRowNumber);}// for Consensus row .... weightage 2 (red color)
                                rowNumber = rowNumber +1;ConsensusRowWeightageRowNumber=newWeightageRowNumber();ConsensusRowWeightageRowNumber.Section= section;ConsensusRowWeightageRowNumber.Lineitem=Li;ConsensusRowWeightageRowNumber.Broker="";ConsensusRowWeightageRowNumber.RowNumber= rowNumber;ConsensusRowWeightageRowNumber.Weightage=(int)RowWeightage.ConsenSusRow;WeightageRowNumberall.Add(ConsensusRowWeightageRowNumber);if(qcTrueDistin.Any(x => x.TabName.Equals(section)&& x.StandardLineItem.Equals(Li))){// for QC Check row .... weightage 3, if any  (yellow color)foreach(var broker inDistinctBroker){//Interlocked.Increment(ref rowNumber);
                                        rowNumber = rowNumber +1;QcRowWeightageRowNumber=newWeightageRowNumber();QcRowWeightageRowNumber.Section= section;QcRowWeightageRowNumber.Lineitem=Li;QcRowWeightageRowNumber.Broker= broker;QcRowWeightageRowNumber.RowNumber= rowNumber;QcRowWeightageRowNumber.Weightage=(int)RowWeightage.QcRow;WeightageRowNumberall.Add(QcRowWeightageRowNumber);}}}}

this way i just populate WeightageRowNumberall for demo purpose but i need to populate at runtime which i did in foreach in above code.

List<WeightageRowNumber>WeightageRowNumberall=newList<WeightageRowNumber>{newWeightageRowNumber{Section="Consensus Model",Lineitem="Net Revenue",Broker="BW",Weightage=1,RowNumber=1},newWeightageRowNumber{Section="Consensus Model",Lineitem="Net Revenue",Broker="3P-1",Weightage=1,RowNumber=2},newWeightageRowNumber{Section="Consensus Model",Lineitem="Net Revenue",Broker="",Weightage=2,RowNumber=3},newWeightageRowNumber{Section="Consensus Model",Lineitem="Net Revenue",Broker="",Weightage=3,RowNumber=4},newWeightageRowNumber{Section="Consensus Model",Lineitem="Net Revenue",Broker="",Weightage=3,RowNumber=5},newWeightageRowNumber{Section="Consensus Model",Lineitem="Cost of Revenue",Broker="BW",Weightage=1,RowNumber=6},newWeightageRowNumber{Section="Consensus Model",Lineitem="Cost of Revenue",Broker="3P-1",Weightage=1,RowNumber=7},newWeightageRowNumber{Section="Consensus Model",Lineitem="Cost of Revenue",Broker="",Weightage=2,RowNumber=8},newWeightageRowNumber{Section="Consensus Model",Lineitem="Cost of Revenue",Broker="",Weightage=3,RowNumber=9},newWeightageRowNumber{Section="Consensus Model",Lineitem="Cost of Revenue",Broker="",Weightage=3,RowNumber=10},newWeightageRowNumber{Section="Key Financials",Lineitem="Quick Ratio",Broker="BW",Weightage=1,RowNumber=11},newWeightageRowNumber{Section="Key Financials",Lineitem="Quick Ratio",Broker="3P-1",Weightage=1,RowNumber=12},newWeightageRowNumber{Section="Key Financials",Lineitem="Quick Ratio",Broker="",Weightage=2,RowNumber=13},newWeightageRowNumber{Section="Key Financials",Lineitem="Quick Ratio",Broker="",Weightage=3,RowNumber=14},newWeightageRowNumber{Section="Key Financials",Lineitem="Quick Ratio",Broker="",Weightage=3,RowNumber=15},};

My WeightageRowNumber class look like

publicclassWeightageRowNumber{publicWeightageRowNumber(){this.Broker=string.Empty;this.Section=string.Empty;this.Lineitem=string.Empty;this.RowNumber=-1;this.Weightage=0;this.Id="-1";}publicstringBroker{get;set;}publicstringSection{get;set;}publicstringLineitem{get;set;}publicintRowNumber{get;set;}publicintWeightage{get;set;}publicstringId{get;set;}}

please tell me how to use LINQ to populate my WeightageRowNumberall instead of foreach loop. if possible guide with code. thanks

How to set parameter datatype in Entity Framework

$
0
0

Hi All,

Below is my store procedure. This procedure includes 3 cases : to insert, update delete 

ALTER PROCEDURE [dbo].[sp_Insert_update_delete]
    -- Add the parameters for the stored procedure here
	@case INT ,
	@emp_id INT=NULL,
       @emp_name VARCHAR(50) = null,
       @city varchar(50)= null

AS
BEGIN

IF @case = 1
    BEGIN
 
    SET NOCOUNT ON;

        INSERT INTO [dbo].[tblEmployee](emp_name,city)
        VALUES(@emp_name,@city)

    SELECT SCOPE_IDENTITY() AS empid
	END

IF @case = 2
    BEGIN
 
        UPDATE [dbo].[tblEmployee]
		SET emp_name=@emp_name,city=@city
		WHERE emp_id=@emp_id

	END
IF @case = 3
    BEGIN
 
        DELETE FROM [dbo].[tblEmployee]
		WHERE emp_id=@emp_id

	END



END

When I validate EDMX it show error

Error 1 Error 2037: A mapping function bindings specifies a function DemoDbModelNameSpace.Store.sp_Insert_update_delete but does not map the following function parameters:case

How to define/use case parameter in EF.

Please suggest.


Query 3 tables using LINQ

$
0
0

Hello all

I have a table that has a one-to-one relationship with another. The other table has a many-to-many relationship with a third table.

salespeople <--> market

location --> market

When I select a location I want to get the email addresses of the salespeople for the market the location is associated with. I would like to use LINQ since it seems the cleanest code for this.

Any suggestions on how to structure this query would be great!

Carlos

What is the meaning of: Database.Log = (sql) => Debug.Write(sql)?

$
0
0

Hi

I have the configuration in EF:

 public class AuraDbContext : DbContext, IQueryableUnitOfWork
    {
        public AuraDbContext() : base("name=AuraDbConnectionString")
        {
            Database.Log = (sql) => Debug.Write(sql);
        }

        public virtual DbSet<Archivo> Archivo { get; set; }
        public virtual DbSet<Bien> Bien { get; set; }
        public virtual DbSet<BienMaterial> BienMaterial { get; set; }
        public virtual DbSet<BienSerie> BienSerie { get; set; }
        public virtual DbSet<BienSerieComponente> BienSerieComponente { get; set; }
        public virtual DbSet<PruebaSAT> PruebasSAT { get; set; }
        public virtual DbSet<Contrato> Contrato { get; set; }
        public virtual DbSet<ContratoBien> ContratoBien { get; set; }
        public virtual DbSet<ContratoBienMaterial> ContratoBienMaterial { get; set; }
        public virtual DbSet<ContratoBienMaterialBom> ContratoBienMaterialBom { get; set; }
        public virtual DbSet<ContratoBienMaterialCaracteristicaTecnica> ContratoBienMaterialCaracteristicaTecnica { get; set; }
        public virtual DbSet<ContratoGarantia> ContratoGarantia { get; set; }
        public virtual DbSet<ContratoGrupoBom> ContratoGrupoBom { get; set; }
        public virtual DbSet<ContratoGrupoBomBien> ContratoGrupoBomBien { get; set; }
        public virtual DbSet<ContratoGrupoContractual> ContratoGrupoContractual { get; set; }
        public virtual DbSet<ContratoGrupoContractualBien> ContratoGrupoContractualBien { get; set; }
        public virtual DbSet<ContratoGrupoContractualBienMaterial> ContratoGrupoContractualBienMaterial { get; set; }
        //public virtual DbSet<ContratoProyecto> ContratoProyecto { get; set; }
        public virtual DbSet<Parametro> Parametros { get; set; }
        public virtual DbSet<ParametroValor> ParametroValores { get; set; }
        public virtual DbSet<Proveedor> Proveedor { get; set; }

What is the meaning of: Database.Log = (sql) => Debug.Write(sql)?

Using a stored procedure with ADO.net

$
0
0

Hi All,

I need to populate 2 textboxes with 2 dates in the onload event of my page using ADO.net in code behind. 

I translated the following SQL query

declare @Today datetime
declare @LastAvailableDay datetime
set @Today = getdate()
set @LastAvailableDay = dateadd(day,+29, @Today)
SELECT DISTINCT @Today, @LastAvailableDay FROM dbo.DateTable

into the below Stored Procedure:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE getOnloadDates 
@Today datetime,
@LastAvailableDay datetime
AS
BEGIN
SET NOCOUNT ON;
SELECT DISTINCT @Today, @LastAvailableDay FROM dbo.DateTable
END
GO

How would you suggest in ADO to specify that @Today should be "getdate()" and @LastAvailableDate should be "dateadd(day,+29, @Today)"?

@Today and @LastAvailableDate should fill the 2 textboxes.

Thank you in advance,
Claudio

How can I create this type of key?

$
0
0

I am tasked with creating a new web application as a replacement for a MS Access form application. The existing application uses a primary key on its main table that is in the following format Gcurrentyear-incrementingnumber for example G2019-02115. I need to keep this format as I will be importing all existing data (around 9000 records) into the new application. This is also a foreign key on a number of other tables. I would like to use EF for the new application but am concerned with how I could create primary keys that would fit my requirement. Does anyone have any idea on how I could accomplish this?

How to SELECT single value in gridview

$
0
0

Hi,

I have a gridview control as below

<asp:GridView ID="GridView1" runat="server" EnableModelValidation="True" AutoGenerateColumns="False" 
            OnRowDataBound="GridView1_RowDataBound"
           OnRowCommand="GridView1_RowCommand"
            CellPadding="4" ForeColor="#333333" GridLines="None" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"><AlternatingRowStyle BackColor="White" /><Columns><asp:TemplateField><ItemTemplate><span class="auto-style14"></span><span><b><span style="color: #2B547E"><span class="auto-style2"><span class="auto-style1" style="color: #000066">User Name:</span><asp:Label ID="UserName" 
                    runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"UserName") %>' CssClass="auto-style1"></asp:Label><span class="auto-style1">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></span></span></b><br /></span><span class="auto-style2">&nbsp;<asp:Button ID="btBuyLot" runat="server" BackColor="#CC0000" CommandName="TakeEarn" Font-Bold="True" ForeColor="White" Height="53px" OnClick="btBuyLot_Click" Text="Click to Claim Earning" Width="186px" CausesValidation="True" /><span class="auto-style7"><span class="auto-style8">[<asp:Label ID="lblUserID" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"UserID") %>' style="font-size: x-small"></asp:Label>
                        ]</span></span><br /><br /></span></ItemTemplate></asp:TemplateField></Columns></asp:GridView>

My C# for gridview databind is as below

protected void Page_Load(object sender, EventArgs e)
        {
            bind1();
        }

        public void bind1()  // Take Referrer earning
        {

            if (!IsPostBack)

                if (!object.Equals(Session["UserId"], null))
                {

                    //**Normal sql connection not of DataBase class**
                    string UserID = Session["UserId"].ToString();
                    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConn"].ToString());

                    using (SqlCommand sqlCmd = new SqlCommand("SELECT  UserID, UserName  FROM Table1 WHERE ID = UserID", con))
                    {
                        con.Open();

                        DataTable dt = new DataTable();
                        dt.Load(sqlCmd.ExecuteReader());

                        GridView1.DataSource = dt;
                        GridView1.DataBind();
                        con.Close();
                    }
                }

        }

what I want to archive from this code is to SELECT a single value WHERE UserId = UserID, but my problem is that when I run the code, it returns all the date in the table including unwanted UserIDs.

Please how else can I code this to be able to SELECT the needed Value by theUserID.

Viewing all 1698 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>