2 Samuel 12:22
And he said, While the child was yet alive, I fasted and wept: for I said, Who can tell whether GOD will be gracious to me, that the child may live? And he said, While the child was yet alive, I fasted and wept: for I said, Who can tell whether GOD will be gracious to me, that the child may live?
This verse belongs to the aftermath of David's murder of Uriah, in which Uriah himself carried his own death-warrant from David to Joab. That order commanded Joab to set Uriah in the forefront of the hottest battle and then retire from him so that he would be smitten and die. Joab obeyed the command, and Uriah fell by the sword of the children of Ammon.
In giving that order David had departed from God and was acting as Satan's agent. Joab in turn transgressed God's law by obeying the king rather than obeying God.
The verse explains David's conduct while his child was still alive: he fasted and wept and pleaded for the child's life. He did so because he hoped God might be gracious to him and spare the child, persisting in pleading while there was still hope. Once the child died he ended his mourning and submitted quietly to the outcome. That quiet acceptance showed continued trust in God's mercy, in which he found comfort.
In this history the verse illustrates how turning away from God's instruction brings disgrace upon a reputation that was once fair and honorable.