Let $f$ : $X\to Y$ be a morphism of schemes. Let $\operatorname{Spec} B$ be an affine open subset of $Y$ such that $B$ is generated by $g_1,g_2......g_m$ and inverse images of $\operatorname{Spec} B_{g_i}$ under $f$ are affine for all $i=1,2....m$. Show that inverse image of $\operatorname{Spec} B$ under $f$ is also affine.
I am not able to use Ex 2.17(b) Hartshorne.
We may assume that $Y=\operatorname{Spec}(B)$. We will make use of Ex. 2.4 of Hartshorne.
Set $A=\Gamma(X,\mathcal{O}_X)$. On the one hand, the morphism $f:X\to \operatorname{Spec}(B)$ corresponds to a ring homomorphism $B\to A$, which in turn induces a morphism $g:\operatorname{Spec}(A)\to \operatorname{Spec}(B)$. On the other hand, the identity $A\to \Gamma(X,\mathcal{O}_X)$ corresponds to a morphism $\Phi:X\to\operatorname{Spec}(A)$. It is easy to see that this a morphism over $\operatorname{Spec}(B)$, that is $g\circ \Phi=f$. We shall prove that $\Phi$ is an isomorphism. This will prove that $X$ is affine. To show that $\Phi$ is an isomorphism, we may restrict ourselves to the case $B=B_{g_i}$. But in this case $X$ is affine by hypothesis, and hence $\Phi$ is an isomorphism of affine schemes.